如何通过一条 SQL 查询获取产品及其购买次数?

发布于 2024-11-07 09:05:18 字数 126 浏览 0 评论 0原文

Buy 有一个外键 product_id

因此,除了SELECT * FROM products;之外,我们还对获取每种产品的购买次数感兴趣。

Buy has a foreign key product_id.

So in addition to SELECT * FROM products; we are interested in getting the number of buys each product has.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

祁梦 2024-11-14 09:05:18

类似这样的事情:

SELECT p.*, COUNT(buy.product_id) FROM product p INNER JOIN buy ON buy.product_id = p.id GROUP BY buy.product_id

应该可以解决问题。

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.

独夜无伴 2024-11-14 09:05:18

连接

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

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
久夏青 2024-11-14 09:05:18
SELECT p.*,COUNT(b.product_id) FROM products p
INNER JOIN buy b ON p.id=b.product_id
GROUP BY b.product_id

这就是我能提供的关于您发布的信息的全部内容。如果上述方法不起作用,两者的表结构都会有很大帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文