[英]How to return rows from left table where condition on right table true on all row without sub query
I have 2 table with this sample data.我有 2 个包含此示例数据的表。
Parent家长
id ID | title标题 |
---|---|
1 1 | A一种 |
2 2 | B乙 |
3 3 | C C |
Childs柴尔兹
id ID | p_id p_id | number数字 |
---|---|---|
1 1 | 1 1 | 1 1 |
2 2 | 1 1 | 2 2 |
3 3 | 1 1 | 3 3 |
4 4 | 2 2 | 4 4 |
5 5 | 2 2 | 5 5 |
6 6 | 2 2 | 6 6 |
7 7 | 3 3 | 2 2 |
8 8 | 3 3 | 7 7 |
9 9 | 3 3 | 8 8 |
10 10 | 3 3 | 9 9 |
And I want to get rows from parents join with childs and number > 3.我想让父母的行与孩子和数字> 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但是我只想接收所有孩子的条件都正确的父母,即使一个孩子的条件不正确,也不应该返回父母
And I want to do without subquery我想不用子查询
SELECT * FROM `parent`
LEFT JOIN `childs` on `childs`.`p_id` = `parent`.`id`
WHERE `childs`.`number` > '3'
I want to get only parent B with this condition.我只想得到这种情况的父母 B。
Thanks.谢谢。
Maybe something like this can work也许这样的事情可以工作
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
Try this:试试这个:
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;
Here's a fiddle demo这是一个小提琴演示
And I want to get rows from parents join with childs and number > 3.我想让父母的行与孩子和数字> 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但是我只想接收所有孩子的条件都正确的父母,即使一个孩子的条件不正确,也不应该返回父母
I would recommend:我会推荐:
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;
There is no reason at all to use strings for what you want to do.完全没有理由将字符串用于您想做的事情。 It just confuses the logic.它只是混淆了逻辑。
An even more efficient method would use NOT EXISTS
:更有效的方法是使用NOT EXISTS
:
select p.*
from p
where not exists (select 1
from childs c
where p.id = c.p_id and c.number <= 3
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.