Home > Back-end >  Python & Sqlite: In sqlite table, I have an id, name, and point. I have a list of ids, I want to sor
Python & Sqlite: In sqlite table, I have an id, name, and point. I have a list of ids, I want to sor

Time:09-17

Making an example that looks similar to what I actually have.

Table I have in Sqlite database:

id1 | A | 13
id2 | B | 24
id3 | C | 35
id4 | D | 32
id5 | E | 16
...

List I will work with:

[id1, id3, id4, id5]

I want to sort this list by points saved in the Sqlite database.

The list would look like this later:

[id4, id2, id5, id1]

This is basically what I want to do for now. I've thought of getting the ids and points of users, and making it into a dictionary in python, but I'm sure how to do that since I'm not experienced with SQLite.

I want to know if theres a way to actually contain the code within SQL queries through more advanced stuff, or if not, the best way I can do it for python.

If the dictionary is a good way to do it, please help me do it. (I've seen some people saying that I should use row factory and such, but idk what that is..)

CodePudding user response:

You can directly do the sorting in the query itself.

Use the following algo:

  1. Send a list of IDs to query
  2. sort it in sql
  3. return the id list back

Try this (not tested but should work):

id_list = [id1, id3, id4, id5]

query="SELECT id FROM sqlitetable WHERE id in ({}) ORDER BY points DESC".format(','.join(['?']*len(id_list)))

cursor.execute(query, id_list)
  • Related