[英]SQL query select return result not in ONE table
Say I have a table people
with a name
field.假设我有一个带有
name
字段的表people
。 In that table are 3 rows with names: Steve, Mark, Ricky
在那个表中有 3 行名字:
Steve, Mark, Ricky
Then I have a list of names: [Shane, Ricky, Mark]
然后我有一个名字列表:
[Shane, Ricky, Mark]
I want to execute one query that will return the values that aren't already in the table.我想执行一个查询,该查询将返回表中尚不存在的值。
I know I can do this with the following:我知道我可以通过以下方式做到这一点:
names = [Shane, Ricky, Mark]
for name in names:
sql = '''SELECT * FROM people WHERE name=%s'''
db.execute(sql, args=name)
results = db.fetchall()
# If no results are returned for a name
# this means the name isn't already in the table.
if not results:
print(name) # This would return 'Shane' as it's not already in the table.
Is there a way I could do this more efficiently with one SQL statement, rather than looping over each name in the list?有没有一种方法可以使用一个 SQL 语句更有效地执行此操作,而不是遍历列表中的每个名称?
您可以使用: SELECT * FROM people WHERE name NOT IN(...)
You can use the SQL IN
operator, selecting the values already in the table;您可以使用 SQL
IN
运算符,选择表中已有的值;
SELECT * FROM people WHERE name IN (...your values...)
and then finding the difference between the two lists:然后找出两个列表之间的差异:
not_in_db = list(set(names).difference(results))
UNTESTED:未经测试:
Generate the list as a table (t1) and then return from that generated table, those values not in your people table.将列表生成为表 (t1),然后从生成的表中返回,这些值不在您的人员表中。
The issue is a database can't return values that don't exist.问题是数据库无法返回不存在的值。 So we first create a temporary table with your values so they exist and can be returned.
因此,我们首先使用您的值创建一个临时表,以便它们存在并可返回。 Then we rub it up against the people table to find those that don't exist;
然后我们在 people 表上摩擦它以找到那些不存在的; thus allowing us to return those names not in people table.
从而允许我们返回不在 people 表中的那些名字。
SELECT *
FROM (values row('Shane'),
row('Ricky'),
row('Mark')) t1 (Name)
WHERE NOT EXISTS (SELECT 1 FROM people P where P.Name = T1.Name)
or perhaps: (I don't think you need to specify a table in mySQL if I recall.)或者:(如果我记得的话,我认为您不需要在 mySQL 中指定一个表。)
SELECT *
FROM (SELECT 'Shane' as Name UNION ALL
SELECT 'Ricky' UNION ALL
SELECT 'Mark') t1
WHERE NOT EXISTS (SELECT 1 FROM people P where P.Name = T1.Name)
So the above is the SQL for your sql =
statement所以上面是你的
sql =
语句的 SQL
Though in both cases we should specify data type for Name be it varchar, nvarchar and length...尽管在这两种情况下,我们都应该为 Name 指定数据类型,无论是 varchar、nvarchar 还是长度...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.