简体   繁体   English

SQL选择关系数是否大于X?

[英]SQL select if count on relation is greater than X?

I have 2 tables 我有2张桌子

" orders " has 1-to-N relation with " articles " 订单 ”与“ 商品 ”具有1对N的关系

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? 我该如何对商品进行子计数,并且仅获得4件或更多商品的订单?

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 . 这是一个连合法使用SELECT *GROUP BY ,因为o.id是(大概)主键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. 这样做的好处是可以在articles(order_id)上使用索引,因此可以具有更好的性能。

Use aggregation with a filter on aggregated result by using HAVING clause 使用HAVING子句对聚合结果使用筛选器聚合

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

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

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