Buy
有一个外键product_id
。
所以除了SELECT * FROM products;
之外,我们还有兴趣了解每个产品的购买数量。
答案 0 :(得分:3)
有些事情:
SELECT p.*, COUNT(buy.product_id) FROM product p INNER JOIN buy ON buy.product_id = p.id GROUP BY buy.product_id
应该这样做。
答案 1 :(得分:1)
SELECT p.*,COUNT(b.product_id) FROM products p
INNER JOIN buy b ON p.id=b.product_id
GROUP BY b.product_id
这就是我发布的所有信息。如果上述方法不起作用,两者的表结构将有助于实现。
答案 2 :(得分:1)
<强>加入强>
SELECT Products.*, COUNT(Buy.ID) AS Bought
FROM products
LEFT OUTER JOIN Buy ON products.ID = Buy.product_id
GROUP BY Buy.product_id
<强>子查询强>
SELECT
Products.*,
(SELECT COUNT(ID) FROM Buy WHERE product_id = Products.ID) AS Bought
FROM products