表A必须与B外连接。
id | ...
---|-----
1 |
2 |
3 |
---|-----
id| a_id | b | ...
--|------|----------
1 |1 | special |
2 |1 | normal |
3 |2 | normal |
4 |2 | normal |
--------------------
所以我想:
a_id | b.id | ...
-----|------|--------
2 | 3 |normal |
2 | 4 |normal |
3 | None |
-----|------|
我的第一个想法是使用嵌套选择,但它并不是最佳选择。
答案 0 :(得分:0)
select distinct a.*
from a join b on a.id=b.a_id
where b.b='special';
排除具有“特殊”
的群组select a.*
from a outer join
(select distinct a.*
from a join b on a.id=b.a_id
where b.b='special') excluded on a.id=excluded.id
having excluded.id is null;
只留下有效的行。
select *
from (select a.*
from a outer join
(select distinct a.*
from a join b on a.id=b.a_id
where b.b='special') excluded on a.id=excluded.id
having excluded.id is null) outer join b on a.id=b.a_id;
外部有效行与b
连接