提问者:小点点

选择包含混合单引号和双引号的元组的查询


Postgreql选择包含带有单引号和双引号的元组的查询,当将此元组作为输入以选择查询时,它会发生错误,指出数据库中不存在特定值。

我有treid转换列表的值JSON列表双引号,但这并没有帮助。

list = ['mango', 'apple', "chikoo's", 'banana', "jackfruit's"]

query = """select category from  "unique_shelf" where  "Unique_Shelf_Names"  in {}""" .format(list)

错误:“chikoo's”列不存在

事实上chikoo确实存在,但由于双引号,它无法获取值。


共1个答案

匿名用户

首先,请不要使用list作为变量名,list是一个保留关键字,您不想覆盖它。

其次,在表和列周围使用“”是不好的做法,用“”代替。

第三,当你格式化一个数组时,它输出为

select category from `unique_shelf` 
where `Unique_Shelf_Names` in (['mango', 'apple', "chikoo's", 'banana', "jackfruit's"])

这不是有效的SQL语法。

您可以用逗号连接所有值

>>>print("""select category from `unique_shelf` where `Unique_Shelf_Names` in {})""".format(','.join(l)))
select category from `unique_shelf` 
where `Unique_Shelf_Names` in (mango,apple,chikoo's,banana,jackfruit's)

这里的问题是括号内的值没有引号。我们可以通过使用双引号(")预先格式化它们来做到这一点

l = ['mango', 'apple', "chikoo's", 'banana', "jackfruit's"]
list_with_quotes = ['"{}"'.format(x) for x in l]

query = """
select category from `unique_shelf` 
where `Unique_Shelf_Names` in ({})""" .format(','.join(list_with_quotes))

这会给你一个输出

select category from `unique_shelf` 
where `Unique_Shelf_Names` in ("mango","apple","chikoo's","banana","jackfruit's")