[英]Select all IDs from x table that are not in column_foo of y table
How do I select all IDs from table_x that are not present in any row of table y in column_foo ? 如何从table_x中选择在column_foo的表y的任何行中不存在的所有ID?
I'm struggling to do this with a single SQL query. 我正在用单个SQL查询来做到这一点。
SELECT id FROM x
WHERE NOT EXISTS (SELECT * FROM y WHERE foo = id)
Or 要么
SELECT id FROM x
WHERE id NOT IN (SELECT foo FROM y)
Or if y.foo
is not a nullable column, you can even do: 或者,如果
y.foo
不是可为空的列,您甚至可以执行以下操作:
SELECT x.id FROM x
LEFT JOIN y ON x.id = y.foo
WHERE y.foo IS NULL
也许您可以执行以下操作:
SELECT id FROM table_x WHERE id NOT IN (SELECT column_foo FROM table_y);
You would use a LEFT JOIN. 您将使用LEFT JOIN。 More explanation and examples here.
更多说明和示例在这里。
It's better to avoid subqueries if you can. 如果可以的话,最好避免子查询。 An
INNER JOIN
will return only rows that meet the join criteria. INNER JOIN
将仅返回满足INNER JOIN
条件的行。
SELECT DISTINCT
x.id
FROM
table_x x
INNER JOIN table_y y ON (x.id = y.id_column_in_y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.