MYSQL:连接表中的所有值都相同

时间:2017-11-08 15:03:34

标签: mysql sql

假设我们有两个表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

现在我卡住了,查询返回逻辑上正确的两行,请问如何重写此查询?

3 个答案:

答案 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 );