简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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