Mysql 选择T1中存在但T2中不存在的id
我有两个表和数据如下Mysql 选择T1中存在但T2中不存在的id,mysql,join,Mysql,Join,我有两个表和数据如下 create table t1 (id int, name varchar(10)); create table t2 (id int, name varchar(10), t1id int); insert into t1 values (1,'value 1'), (2,'value 2'), (3,'value 3'), (4,'value 3'); insert into t2 values (1,'value 1',1), (2,'value 2',1),
create table t1 (id int, name varchar(10));
create table t2 (id int, name varchar(10), t1id int);
insert into t1 values
(1,'value 1'),
(2,'value 2'),
(3,'value 3'),
(4,'value 3');
insert into t2 values
(1,'value 1',1),
(2,'value 2',1),
(3,'value 3',1),
(4,'value 3',2);
我想要的是T1(id)中的id列表,而不是T2(t1id)中的id列表
产出将是
3,4 as t1.id(3,4)在T2(t1id)中不存在
为什么我总是在问问题后得到答案
select id FROM t1 WHERE id NOT IN (select distinct(t1id) FROM t2);
当您在中有许多(不同的)记录时,请尽量避免在中出现
t2@Peter:实际上,现代DBMS优化不存在
,不存在
和左连接
解决方案的方式非常相似
select id FROM t1 WHERE id NOT IN (select distinct(t1id) FROM t2);