标题听起来有点奇怪,但我想要做的是如下。给出表格
A.a A.b B.a B.c B.d
--- --- --- --- ---
1 X 1 10 Z
2 Y 1 30 W
我想要的查询可能类似于以下内容:
SELECT A.a, B.d FROM A
some kind of JOIN B ON A.a = B.a
...WHERE A.a = :a AND B.c = :c
现在,如果我进行以下替换,我想得到这些答案:
:a :c A.a B.d
-- -- --- ---
1 10 --> 1 Z
1 20 --> 1 NULL
2 any --> empty set
我正在使用MySQL,所以FULL JOIN是不可能的。
未解决
我以为我自己解决了这个问题:
SELECT A.a, CASE WHEN B.c = :c THEN B.d ELSE NULL FROM A
LEFT JOIN B ON A.a = B.a
WHERE A.a = :a AND B.c = :c
但是这给了:
:a :c A.a B.d
-- -- --- ---
1 20 --> 1 NULL
1 10
答案 0 :(得分:3)
试试这个:
select distinct a1.a, b2.d from A a1
join B b1 on a1.a = b1.a
left join B b2 on a1.a = b2.a and b2.c = 10
where a1.a = 1