[英]How to get products and the number of buys each has with one SQL query?
Buy
has a foreign key product_id
. Buy
有一个外键product_id
。
So in addition to SELECT * FROM products;
因此除了
SELECT * FROM products;
we are interested in getting the number of buys each product has. 我们有兴趣获取每种产品的购买数量。
Something along the lines of: 类似于以下内容:
SELECT p.*, COUNT(buy.product_id) FROM product p INNER JOIN buy ON buy.product_id = p.id GROUP BY buy.product_id
should do the trick. 应该可以。
SELECT p.*,COUNT(b.product_id) FROM products p
INNER JOIN buy b ON p.id=b.product_id
GROUP BY b.product_id
Thats about all I can offer with the info you've posted. 那就是我所能提供的所有信息。 Table structure of both would help a ton if the above doesn't work.
如果上述方法不起作用,两者的表结构都会帮助很多。
Join 加入
SELECT Products.*, COUNT(Buy.ID) AS Bought
FROM products
LEFT OUTER JOIN Buy ON products.ID = Buy.product_id
GROUP BY Buy.product_id
Subquery 子查询
SELECT
Products.*,
(SELECT COUNT(ID) FROM Buy WHERE product_id = Products.ID) AS Bought
FROM products
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.