【问题标题】:Python MySQL executemany in WHERE clausePython MySQL 在 WHERE 子句中执行许多
【发布时间】:2013-08-17 23:24:58
【问题描述】:

我想从 MySQL 中选择值如下

do_not_select = [1,2,3]

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

查询返回数据库中除第一个 id (1) 之外的所有值。但是,我不希望它选择 id 1,2 或 3。

这可以使用 executemany 命令吗?

【问题讨论】:

    标签: python mysql-python


    【解决方案1】:

    NOT IN一个机会:

    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()
    

    我怀疑(虽然我没有测试过)这会更好 id do_not_select 是一个元组,然后我认为你可以直接在你的查询中触发它:

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

    我很想知道这是否有效 - 如果您尝试,请告诉我 :)

    【讨论】:

    • 这在我输入它们时有效,但如果我使用我的 do_not_select 列表输入它们则无效......?
    • 你需要将 do_not_select 解压到条件中,我会在上面更新
    • 真的很好!我总是使用带有一些参数的 %s 而不是 .format()。从现在开始我会这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2019-12-10
    • 2015-11-03
    相关资源
    最近更新 更多