我想从表1中选择不在表2中的数据,但我必须从表1中选择特定的数据
我的数据表
CREATE TABLE IF NOT EXISTS `table3` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`acc_id` int(11) NOT NULL DEFAULT '0',
`did` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `table2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`acc_id` int(11) NOT NULL,
`table1_id` int(11) NOT NULL,
`did` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `table1` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`acc_id` int(11) NOT NULL DEFAULT '0',
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
)
我想要做
从table1中选择名称,id,其中id!=(从table2中选择table1_id将table2上的table3加入到table2.acc_id = table3.acc_id中,其中table2.did = 4759505和table2.acc_id = 2)和table1.acc_id = 2
如果子查询返回1行,则上面的查询可以正常工作,但是如果子查询返回多行,则上述查询无法正常工作
谢谢
您可以将更!=
改为not in
:
select name, id
from table1
where id not in (select table1_id
from table2 join
table3
on table2.acc_id = table3.acc_id
where table2.did = 4759505 and table2.acc_id = 2
) and
table1.acc_id = 2;
注意:您还应该确保table1_id
在子查询中从不NULL
。NOT IN
在这种情况下可能是非直觉的。通常,我更喜欢NOT EXISTS
:
select name, id
from table1
where not exists (select table1_id
from table2 join
table3
on table2.acc_id = table3.acc_id
where table2.did = 4759505 and table2.acc_id = 2 and
table1_id = table1.id
) and
table1.acc_id = 2;
这样可以NULL
更直观地处理该值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句