如何从ids
中选择所有table_1
并包括表二同时具有KR
和BR
状态的条目? group by table_1.id having count(table_1.id) > 1
的每个条目仅包含一个ID,我都需要它们。 where in ('KR', 'BR')
会给我或者。所以我需要有效地拥有where entry exist in table_2 AND has an entry for BOTH KR and BR
table_1
id |
===+
1 |
===+
2 |
===+
3 |
===+
table_2
通过table_1
与table_1_id
相关
table_2
id | table_1_id | status
===+============+=======
1 | 1 | KR
===+============+=======
2 | 1 | BR
===+============+=======
3 | 2 | KR
===+============+=======
4 | 3 | KR
===+============+=======
5 | 3 | BR
===+============+=======
在上面的示例中,输出为
t_1.id | t_2.id | t_2.status
=======+========+===========
1 | 1 | KR
=======+========+===========
1 | 2 | BR
=======+========+===========
3 | 4 | KR
=======+========+===========
3 | 5 | BR
=======+========+===========
在此结果集中,table_1.id = 3
将被忽略,因为它不包含两个状态的条目,如何实现呢?
编辑:我也尝试过having group_concat(table_2.status) in ("KR, BR")
但每个条目仍然只有一个。
答案 0 :(得分:2)
有很多方法可以给这只猫剥皮,但是如何呢?
SELECT t_1.ID, t_2.id, t_2.status
FROM table_1 t_1
INNER JOIN table_2 t_2 ON t_1.id = t_2.table_1_id
WHERE t_1.ID IN (SELECT table_1_id FROM table_2 WHERE status = 'KR')
AND t_1.ID IN (SELECT table_1_id FROM table_2 WHERE status = 'BR')
这可能会为您提供更多具有其他状态的行,因此您可能需要将其添加到where子句:
AND t_2.status in ('KR', 'BR')