我可以将这两个SQL查询合并为一个吗?

时间:2015-03-22 14:43:17

标签: mysql sql select

drink_orders有很多drink_order_extras

第一个:

SELECT
  Sum(drink_orders.quantity * drink_orders.drink_price) AS drink_total
FROM
  drink_orders
WHERE
  drink_orders.reservation_id = 3610

第二个

SELECT
  Sum(drink_order_extras.quantity * drink_order_extras.drink_price) AS extra_total
FROM
  drink_order_extras INNER JOIN
  drink_orders ON drink_order_extras.drink_order_id = drink_orders.id
WHERE
  drink_orders.reservation_id = 3610

获得总计(drink_total + extra_total)

也很不错

仅供参考,以下会产生正确的总和:

SELECT
  Sum(drink_orders.quantity * drink_orders.drink_price) AS drink_total,
  Sum(drink_order_extras.quantity * drink_order_extras.drink_price) AS extra_total
FROM
  drink_order_extras INNER JOIN
  drink_orders ON drink_order_extras.drink_order_id = drink_orders.id
WHERE
  drink_orders.reservation_id = 3610

修改

Gordon Linoff的回答很有效:

SELECT Sum(do.quantity * do.drink_price) AS drink_total,
   Sum(extras_total) as extras_total,
   (Sum(do.quantity * do.drink_price) + COALESCE(Sum(extras_total), 0)
   ) as total
FROM drink_orders do LEFT JOIN
 (SELECT doe.drink_order_id,
         Sum(doe.quantity * doe.drink_price) as extras_total
  FROM drink_order_extras doe
  GROUP BY drink_order_id
 ) doe
 ON do.id = doe.drink_order_id
WHERE do.reservation_id = 3610;

2 个答案:

答案 0 :(得分:3)

你在两个不同的方面进行总结。 join导致了笛卡尔积 - 它会抛出总和。您可以在加入前通过聚合来解决此问题:

SELECT Sum(do.quantity * do.drink_price) AS drink_total,
       Sum(extras_total) as extras_total,
       (Sum(do.quantity * do.drink_price) + COALESCE(Sum(extras_total), 0)
       ) as total
FROM drink_orders do LEFT JOIN
     (SELECT doe.drink_order_id,
             Sum(doe.quantity * doe.drink_price) as extras_total
      FROM drink_orders_extras doe
      GROUP BY drink_order_id
     ) doe
     ON do.id = doe.drink_order_id
WHERE do.reservation_id = 3610;

首先将额外费用计入饮品订单。然后它将所有饮料订单信息汇总为预订级别。

答案 1 :(得分:0)

试试这个:

select sum(total) from (
SELECT
  Sum(drink_orders.quantity * drink_orders.drink_price) AS total
FROM
  drink_orders
WHERE
  drink_orders.reservation_id = 3610

UNION

SELECT
  Sum(drink_order_extras.quantity * drink_order_extras.drink_price) AS total
FROM
  drink_order_extras INNER JOIN
  drink_orders ON drink_order_extras.drink_order_id = drink_orders.id
WHERE
  drink_orders.reservation_id = 3610
) t