使用一个查询确保所有值都存在于 table 中
Make sure all values exist in a table with one query
所以我有一个简单的 table 城镇,有芬兰语和瑞典语的名字:
CREATE TABLE town (id SERIAL PRIMARY KEY, name_fi TEXT, name_sv TEXT);
而且我需要检查某个特定城镇是否存在。这很容易:
cursor.execute(
"SELECT EXISTS ( SELECT 1 FROM town WHERE name_fi=%s OR name_sv=%s )",
(town, town)
)
result = cursor.fetchone() # True/False
但现在我需要对多个城镇执行此操作以确保它们全部 存在:
for town in towns:
# Code for one town from above
if result is False:
return False
return True
有没有一种方法可以通过一个查询而不是使用 Python for
循环来做到这一点?
将城镇作为列表传递:
cities = ['Paris', 'London']
template = ','.join(['%s'] * len(cities))
根据需要加入和聚合:
query = '''
select bool_and(name_fi is not null or name_sv is not null)
from
town
right join
(values {}) s (name) on name in (name_fi, name_sv)
'''.format(template)
print (cursor.mogrify(query, [tuple((city,)) for city in cities]).decode('utf8'))
cursor.execute(query, [tuple((city,)) for city in cities])
结果是 True
或 False
print cursor.fetchone()[0]
输出:
select bool_and(name_fi is not null or name_sv is not null)
from
town
right join
(values ('Paris'),('London')) s (name) on name in (name_fi, name_sv)
True
对于 Python 部分 check this answer
所以我有一个简单的 table 城镇,有芬兰语和瑞典语的名字:
CREATE TABLE town (id SERIAL PRIMARY KEY, name_fi TEXT, name_sv TEXT);
而且我需要检查某个特定城镇是否存在。这很容易:
cursor.execute(
"SELECT EXISTS ( SELECT 1 FROM town WHERE name_fi=%s OR name_sv=%s )",
(town, town)
)
result = cursor.fetchone() # True/False
但现在我需要对多个城镇执行此操作以确保它们全部 存在:
for town in towns:
# Code for one town from above
if result is False:
return False
return True
有没有一种方法可以通过一个查询而不是使用 Python for
循环来做到这一点?
将城镇作为列表传递:
cities = ['Paris', 'London']
template = ','.join(['%s'] * len(cities))
根据需要加入和聚合:
query = '''
select bool_and(name_fi is not null or name_sv is not null)
from
town
right join
(values {}) s (name) on name in (name_fi, name_sv)
'''.format(template)
print (cursor.mogrify(query, [tuple((city,)) for city in cities]).decode('utf8'))
cursor.execute(query, [tuple((city,)) for city in cities])
结果是 True
或 False
print cursor.fetchone()[0]
输出:
select bool_and(name_fi is not null or name_sv is not null)
from
town
right join
(values ('Paris'),('London')) s (name) on name in (name_fi, name_sv)
True
对于 Python 部分 check this answer