简体   繁体   English

从x表中选择所有不在y表的column_foo中的ID

[英]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. 更多说明和示例在这里。

Visual Joins 视觉联接

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.

相关问题 Mysql如何从一个表中选择列值不是X和Y的所有记录 - Mysql How to select all records from one table where column value is not both X and Y 表X中购买了表Y中所有产品的那些客户ID的列表? - list of those Customer IDs from Table X who have bought all of the products from Table Y? 从表和唯一列y中选择ID - select id from table and distinct column y SELECT *以及与同一表的另一列的ID相关联的所有行 - SELECT * plus all rows that are associated with the IDs of another column of the same table 从表WHERE`column` = x中选择*如果`column`!= -1 - Select * from table WHERE `column` = x if `column` != -1 有什么更好的方法来查找表 Y 中与表 X 的 PK 相关的所有 ID 是否都存在于 mysql 的表 Z 中? - What's a better way to find if all the ids in table Y related to PK of table X are present in table Z in mysql? SQL如果y.table1 = y.table2有多个表,则从table2中选择x行 - SQL Select x-row from table2 if y.table1=y.table2 multiple tables 哪个更快:“SELECT * FROM table”或“SELECT x,y,q FROM table”(来自包含4个字段的表) - Which is faster: “SELECT * FROM table” or “SELECT x,y,q FROM table” (from a table with 4 fields) 从另一张表的一列中的多个值中选择唯一的ID - Select unique ids from multi values on one column in another table 从表中选择相同的SUM,同一列选择两个不同的ID - Select same SUM from table and same column two different ids
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM