我想从table1中选择不在table2中的数据,但我必须从table1中选择一个特定的数据
我的数据表
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`)
)
我想要做
select name,id from table1 where id !=(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
如果子查询返回1行,则上面的查询很好,但如果子查询返回多行则不会
谢谢
1 回答
您只需将
!=
更改为not in
:注意:您还应确保子查询中的
table1_id
永远不会NULL
. 在这种情况下,NOT IN
可能不直观 . 通常,我更喜欢NOT EXISTS
:这样可以更直观地处理
NULL
值 .