带列表变量的查询

krcsximq  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(225)

我列了一个id的列表,每个值都是int类型

temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]

type(tempasn) 
list

这样做有效:

Temp = pd.read_sql("select count(*) as count\
                    from "+db+"\
                    where ids in (7922, 7018, 5650, 209, 21928, 2294, 10507, 3623)\
                    order by count desc limit 10", conn)

我想把列表中的变量添加到我的查询中
这会导致错误

Temp = pd.read_sql("select count(*) as count\
                    from "+db+"\
                    where ids in "+temp_id+"\
                    order by count desc limit 10", conn)

TypeError: Can't convert 'list' object to str implicitly

我不明白我需要改变什么
回答
最终采纳了下面的评论并修改了生成临时ID的循环:

temp_id = []
for id in df['ID']:
    if id and id not in temp_id:
        temp_id.append(str(ID))        

        #Convert to list format
temp_id = ", ".join(temp_id)

有两件事让这件事成功了:

str(ID) & temp_id = ", ".join(temp_id)
nkoocmlb

nkoocmlb1#

您需要将变量存储为逗号分隔的字符串,而不是数组。
所以声明temp\u id为string。

temp_id = "7922, 7018, 5650, 209, 21928, 2294, 10507, 3623"

Temp = pd.read_sql("select count(*) as count\
                    from "+db+"\
                    where ids in ("+temp_id+")\
                    order by count desc limit 10", conn)
8dtrkrch

8dtrkrch2#

你需要一个字符串,所以你应该内爆你的数组

temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]

my_string = ",".join(temp_id )

Temp = pd.read_sql("select count(*) as count\
                    from "+db+"\
                    where ids in ("+my_string+")\
                    order by count desc limit 10", conn)

相关问题