I am using Python
and PyMySQL
. I want to fetch a number of items from a MySQL database according to their ids:
items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids};"
I am using the formatted string literals (f" "
, https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) to evaluate the tuple inside the SQL statement.
However,I want to get back the items in the order specified by the tuple so firstly the item with item_id = 3
and then the item with item_id = 2
. To accomplish this I have to use the ORDER BY FIELD
clause (see also here: Ordering by the order of values in a SQL IN() clause).
But if I write something like this:
items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{(item_id,) + items_ids};"
then item_id
in the ORDER BY FIELD
clause is considered as an undeclared python variable
and if I write something like this:
items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{('item_id',) + items_ids};"
then item_id
in the ORDER BY FIELD
clause is considered as a string and not as a SQL variable and in this case ORDER BY FIELD
does not do anything.
How can I evaluate the tuple (item_id,) + items_ids
in the SQL statement by maintaining item_id
as a SQL variable in the ORDER BY FIELD
clause?
Obviously I can sort the items after they have returned from the database according to items_ids
and without bothering so much with MySQL but I was just wondering how to do this.