2

I want to select values from MySQL as follows

do_not_select = [1,2,3]

cursor = database.cursor() 
 cursor.executemany("""SELECT * FROM table_a WHERE id != %s""",(do_not_select))
data = cursor.fetchall()

The query return all the values in the db apart form the first id (1). I don't want it to select id 1,2 or 3 however.

Is this possible using the executemany command..?

Jim
  • 1,337
  • 5
  • 20
  • 29

1 Answers1

2

Give NOT IN a go:

do_not_select = [1, 2, 3]

cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN ({}, {}, {})""".format(do_not_select[0],
                                                           do_not_select[1],
                                                           do_not_select[2]))
data.cursor.fetchall()

I suspect (though I haven't tested this) that this would work better id do_not_select was a tuple, then I think you could just fire it straight into your query:

do_not_select = (1, 2, 3)
cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN {}""".format(do_not_select))
data.cursor.fetchall()

I'd be interested to know if this works - if you try it please let me know :)

Nick Burns
  • 973
  • 6
  • 4