对于下表,是否可以使用自连接得到结果?
表:
id pId type
-------------
1 1000 1
2 1001 1
3 1002 1
4 1000 3
预期结果:
id pId type
-------------
2 1001 1
3 1002 1
换句话说,我想要所有具有类型 1 但不具有类型 3 的行。
提前谢谢您。
<小时/>更新
这是性能测试背景下的一个问题。 换句话说,有很多行,例如 1000、1001、1002。
我正在尝试使用当前的表结构来提高性能。 但我知道这张 table 可能也设计得不好。
最佳答案
您不需要任何联接 - 只需要一个子选择 - 像这样:
select * from mytable t1
where not exists (select id from mytable t2 where t1.pid=t2.pid and type=3)
关于mysql - sql自连接中根据特定条件获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183533/