简体   繁体   中英

SQL select if count on relation is greater than X?

I have 2 tables

" orders " has 1-to-N relation with " articles "

SELECT `orders`.* FROM `orders` INNER JOIN `articles` ON 
`articles`.`orders_id` = `orders`.`id` where ????

How can I make a sub-count on articles and get only orders with 4 or more articles?

Thanks you for help!

You can do this as:

SELECT o.*
FROM orders o INNER JOIN
     articles a
     ON a.orders_id = o.id
GROUP BY o.id
HAVING COUNT(*) >= 4; 

This is even a legitimate use of SELECT * with GROUP BY , because o.id is (presumably) the primary key on orders .

Another method is:

select o.*
from orders o
where (select count(*)
       from articles a
       where a.order_id = o.id
      ) >= 4;

This has the advantage that it can use an index on articles(order_id) , so it can have better performance.

Use aggregation with a filter on aggregated result by using HAVING clause

SELECT `o`.*
FROM `orders`  o
INNER JOIN `articles`  a
ON `a`.`orders_id` = `o`.`id`
GROUP BY o.id
HAVING COUNT(DISTINCT a.id) >=4

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