假设我们有两个表pw.write("1");
和A
。
表A
B
表B
id name
1 first row
2 second row
因此,我希望从表id table_a_id voided
1 1 true
2 1 true
3 2 false
4 2 true
中选择所有行,前提是表A
中的所有条目都标记为无效。
我从简单的查询开始
B
现在我卡住了,查询返回逻辑上正确的两行,请问如何重写此查询?
答案 0 :(得分:2)
您可以使用:
SELECT a.id, a.name
FROM a
JOIN b
ON a.id = b.table_a_id
GROUP BY a.id, a.name
HAVING SUM(CASE WHEN voided THEN 0 ELSE 1 END) = 0;
<强> DBFiddle Demo 强>
更简单(没有CASE
):
SELECT a.id, a.name
FROM a
JOIN b
ON a.id = b.table_a_id
GROUP BY a.id, a.name
HAVING SUM(NOT voided) = 0;
-- HAVING NOT SUM(NOT voided);
答案 1 :(得分:0)
您可以使用NOT EXISTS
子句:
SELECT *
FROM table_a as a
where not exists (select *
from table_b as b
where a.id=b.id and not b.voided);
答案 2 :(得分:0)
select *
from table_a
where id not in (select table_a_id
from table_b
where voided = false );