简体   繁体   English

在相关表上选择SQL语句

[英]Select SQL statement on related tables

I have two tables T1 and T2. 我有两个表T1和T2。 I want to select all rows from T2 table where t1_id not equal to any id in T1 table. 我想从T2表中选择所有行,其中t1_id不等于T1表中的任何id。 This is not working: 这不起作用:

SELECT t2.id, t2.t1_id, t2.data FROM T2.t2, T1.t1 WHERE t2.t1_id != t1.id

You could use subquery with NOT IN clause as below: 您可以将子查询与NOT IN子句一起使用,如下所示:

SELECT t2.id, t2.t1_id, t2.data 
FROM T2 t2
WHERE t2.t1_id NOT IN (SELECT DISTINCT id
                       FROM T1)

Use LEFT JOIN to fetch all records from left table and add where condition with checking of null value of second table to find unmatched records of left table 使用LEFT JOIN从左表中获取所有记录,并添加where条件并检查第二个表的空值以查找左表中不匹配的记录

Try this: 尝试这个:

SELECT t2.id, t2.t1_id, t2.data 
FROM T2.t2
LEFT OUTER JOIN T1.t1 ON t2.t1_id = t1.id
WHERE t1.id IS NULL
SELECT t2.id, t2.t1_id, t2.data 
FROM T2.t2
LEFT JOIN T1.t1 ON t2.t1_id = t1.id
GROUP BY t2.id, t2.t1_id, t2.data
HAVING sum(t1.id is not null) = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM