0

有比我更快的解决方案吗?

我有一个包含 orders_id 和 products_id 列的表(无法更改)

现在我想知道有多少订单使用唯一 products_id。

我尝试了以下。但是它在加载太多行(160'000)时崩溃。

    SELECT  DISTINCT `products_id` ,  `products_name` , COUNT(*) as totalorders FROM  `orders_products` ORDER BY  `products_id` ASC 

我也尝试了子查询,但问题与上述相同。

    SELECT (SELECT count(*) FROM orders_products WHERE products_id = op.products_id) AS totalorders, products_id, products_name FROM orders_products op ORDER BY products_id ASC
4

2 回答 2

0

怎么样:

SELECT `products_id`, `products_name`, COUNT(*) FROM `orders_products` GROUP BY (`products_id`, `products_name`) ORDER BY `products_id`
于 2013-10-30T15:52:45.117 回答
0

希望您对 products_id 有一个索引

在这种情况下,我会尝试以下方法:

select products_id, Min(Products_Name), count(*) as TotalOrders from Orders_Products Group by Products_ID Order by Products_ID asc

您可以通过其他几种方式获取 products_name,例如将其包含在您的分组中(还有其他一些含义)。

于 2013-10-30T15:55:34.540 回答