如何 return 行从左边 table where condition on right table true on all row without sub query

How to return rows from left table where condition on right table true on all row without sub query

我有 2 table 个样本数据。

Parent

id title
1 A
2 B
3 C

孩子

id p_id number
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5
6 2 6
7 3 2
8 3 7
9 3 8
10 3 9

我想从 parents 中获取行,加入 childs 并且数字 > 3.

但我只想接收条件在所有 child 上都正确的 parent,即使条件在一个 child 上不正确,parent 不应返回

我想不用子查询

SELECT * FROM `parent` 
LEFT JOIN `childs` on `childs`.`p_id` = `parent`.`id` 
WHERE `childs`.`number` > '3'

这个条件我只想得到parent B

谢谢。

也许这样的事情可以工作

SELECT *
FROM parent p, child c2
WHERE EXISTS ( SELECT * 
          FROM child c1 
          WHERE p.id = c1.p_id AND c1.number >3)  AND  p.id = c2.p_id AND c2.number <=3

试试这个:

SELECT p.id, p.title, GROUP_CONCAT(number ORDER BY number) val
  FROM Parent p JOIN Childs c ON p.id=c.p_id
  GROUP BY p.id, p.title
  HAVING SUBSTRING_INDEX(val,',',1) > 3;

这是一个fiddle demo

And I want to get rows from parents join with childs and number > 3.

But I want to receive only parent whose condition is correct on all childs, and even if the condition is not correct on one child, the parent should not be returned

我会推荐:

SELECT p.id, p.title
FROM Parent p JOIN
     Childs c
     ON p.id = c.p_id
GROUP BY p.id, p.title
HAVING MIN(number) > 3;

根本没有理由为您想做的事情使用字符串。它只是混淆了逻辑。

更有效的方法是使用 NOT EXISTS:

select p.*
from p
where not exists (select 1
                  from childs c
                  where p.id = c.p_id and c.number <= 3
                 );