简体   繁体   English

Mysql-选择少于x个“子行”的行

[英]Mysql - Select rows which have less than x “child rows”

I got a table like this: 我有一张这样的桌子:

planet_id | planet_name

1         | Test planet
2         | Test planet 2

I got a second table like this 我有第二张桌子

area_id   | area_name   | planet_id
1         | test_area   | 1

I need a select query to only select planets which have less than 5 areas. 我需要一个选择查询来仅选择面积小于5的行星。 How do I do that? 我怎么做?

you can group by planets joined with areas and group by the planets. 您可以将按区域划分的行星分组并按行星分组。 you can then use having to filter 然后您可以使用过滤

select one.planet_id, one.planet_name
from first_table one
join second_table two
on (one.planet_id = two.planet_id)
group by one.planet_id, one.planet_id
having count(two.area_id) < 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM