获得热门产品已售出?

问题描述 投票:0回答:2

我正在使用子查询来获得在order_products表中出售的热门产品。

SELECT 
   products.name, 
   (SELECT count(product_id) FROM order_products WHERE order_products.product_id = products.id) as total FROM products 
ORDER BY total DESC LIMIT 10

这个查询似乎工作正常但我觉得有更好的方法而不是使用子查询?

我尝试使用GROUP BY order_products.product_idcount(),但我得到聚合SQL错误。

mysql database
2个回答
0
投票

将子查询重构为连接,类似这样。

SELECT 
    products.name, 
    COUNT(*) AS count
FROM
   products
JOIN
   order_products ON order_products.product_id = products.id
GROUP BY
   products.name
ORDER BY COUNT(*) DESC
LIMIT 10

这几乎等同于你所拥有的。但它以许多SQL程序员更容易阅读的方式表达了您的意图。而且,许多MySQL版本中的查询规划器都可以很好地完成这项工作,但是它们可能不适用于子查询版本。

编辑GROUP BY中提到的列也应出现在SELECT子句中。如果您希望同时显示产品ID和产品名称,请使用此类查询。

SELECT 
    products.id, products.name, 
    COUNT(*) AS count
FROM
   products
JOIN
   order_products ON order_products.product_id = products.id
GROUP BY
   products.id, products.name
ORDER BY COUNT(*) DESC
LIMIT 10

你可能会说SELECT products.nameGROUP BY products.id。但要实现这一点,您需要依赖于MySQL的弃用功能或SQL99的可选功能。许多程序员喜欢避免这样的事情。阅读本文以获取更多信息。 https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


0
投票

以下sql将帮助你。

SELECT products.name,count(*)FROM order_products INNER JOIN产品ON order_products.product_id = products.id GROUP BY products.name ORDER BY COUNT(*)DESC LIMIT 10;

由于您选择的是product.name,因此应在group by子句中使用相同的字段。

您可以通过阅读以下链接中的规则1来了解实际原因:http://www.informit.com/articles/article.aspx?p=664143&seqNum=6

© www.soinside.com 2019 - 2024. All rights reserved.