2

我有这样的查询

SELECT o.product_id,
       p.name,
       count(o.product_id) AS total_products_sold,
       (SELECT count(o.id)
        FROM ebay.`order` o) AS total_orders
FROM ebay.`order` o
INNER JOIN product p ON o.product_id = p.id
GROUP BY o.product_id

对我不想要的每个执行时,都会重新运行 total_orders。一世

问题:

我希望 total_orders 与外部查询的每个结果集相结合。

我试过了,但它只返回 1 行

SELECT tps.product_id,
       tps.name,
       tps.total_products_sold,
       count(oo.id) AS total_orders
FROM ebay.`order` oo
INNER JOIN
  ( SELECT o.id,
           o.product_id,
           p.name,
           count(o.product_id) AS total_products_sold
   FROM ebay.`order` o
   INNER JOIN product p ON o.product_id = p.id
   GROUP BY o.product_id ) AS tps ON oo.product_id = tps.product_id

有更好的解决方案吗?

谢谢。

4

2 回答 2

2

您可以使用with rollupwhich 将在不更改实际查询的情况下为您提供总计它不会在每一行的列中为您提供结果,但您将在最后一行中获得总订单的结果。

SELECT 
  o.product_id,
  p.name,
  count(distinct o.id) AS totalorder
FROM 
  ebay.`order` o
INNER JOIN 
  product p 
ON 
  o.product_id = p.id
GROUP BY 
  o.product_id
WITH ROLLUP

例如

+-----------+------+------------+
| product_id| name | totalorder |
+-----------+------+------------+
|      2000 |   A  |     10     |
|      2001 |   B  |     20     |
|      NULL | NULL |     30     |   <--- Last row is having the Total order 
+-----------+------+------------+

带汇总

于 2013-04-09T07:54:09.713 回答
1
SELECT  tps.product_id,
        tps.name,
        tps.total_products_sold,
        s.total_orders
FROM    ebay.`order` oo
        INNER JOIN
        ( 
            SELECT  o.id,
                    o.product_id,
                    p.name,
                    count(o.product_id) AS total_products_sold
            FROM    ebay.`order` o
                    INNER JOIN product p 
                        ON o.product_id = p.id
            GROUP   BY o.product_id 
        ) AS tps ON oo.product_id = tps.product_id
        CROSS JOIN
        (
            SELECT  count(id) total_orders
            FROM    ebay.`order`
        ) s
于 2013-04-09T07:48:07.210 回答