如何实现count(id)>而不使用groupby的效果

hwazgwia  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(250)

如何选择全部 idstable_1 并包括表2同时具有 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
===+============+=======

  1. 在上面的例子中,输出是

t_1.id | t_2.id | t_2.status
=======+========+===========
1 | 1 | KR
=======+========+===========
1 | 2 | BR
=======+========+===========
3 | 4 | KR
=======+========+===========
3 | 5 | BR
=======+========+===========

  1. 在这个结果集中, `table_1.id = 3` 将被忽略,因为它不包含两种状态的条目,如何实现这一点?
  2. 编辑:我也尝试过 `having group_concat(table_2.status) in ("KR, BR")` 但仍然只有一个条目。
sdnqo3pr

sdnqo3pr1#

给这只猫剥皮有很多方法,但是这个怎么样?

  1. SELECT t_1.ID, t_2.id, t_2.status
  2. FROM table_1 t_1
  3. INNER JOIN table_2 t_2 ON t_1.id = t_2.table_1_id
  4. WHERE t_1.ID IN (SELECT table_1_id FROM table_2 WHERE status = 'KR')
  5. AND t_1.ID IN (SELECT table_1_id FROM table_2 WHERE status = 'BR')

这可能会为您提供更多具有其他状态的行,因此您可能需要将其添加到where子句中:

  1. AND t_2.status in ('KR', 'BR')

相关问题