我正在使用子查询来获得在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_id
与count()
,但我得到聚合SQL错误。
将子查询重构为连接,类似这样。
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.name
和GROUP BY products.id
。但要实现这一点,您需要依赖于MySQL的弃用功能或SQL99的可选功能。许多程序员喜欢避免这样的事情。阅读本文以获取更多信息。 https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
以下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