Home >Database >Mysql Tutorial >How to Execute a SELECT Query with an IN Clause Using MySQLdb?
Executing "SELECT ... WHERE ... IN ..." using MySQLdb
When attempting to execute a SELECT query with an IN clause using MySQLdb, users may encounter issues where no rows are returned despite the query working as expected from the mysql command-line. This can occur due to unnecessary quotes being placed around the IN values.
To overcome this issue, manual construction of the query parameters is required. In both Python 2 and 3, a comma-separated string of placeholders (%s) can be generated from the list of IN values. The query can then be formatted using this string and executed with the original list of values.
For Python 3:
<code class="python">args=['A', 'C'] sql='SELECT fooid FROM foo WHERE bar IN (%s)' in_p=', '.join(list(map(lambda x: '%s', args))) sql = sql % in_p cursor.execute(sql, args)</code>
For Python 2:
<code class="python">args=['A', 'C'] sql='SELECT fooid FROM foo WHERE bar IN (%s)' in_p=', '.join(map(lambda x: '%s', args)) sql = sql % in_p cursor.execute(sql, args)</code>
By following this approach, the SQL query will be correctly formatted with the desired IN values, resolving the issue where no rows were returned previously.
The above is the detailed content of How to Execute a SELECT Query with an IN Clause Using MySQLdb?. For more information, please follow other related articles on the PHP Chinese website!