gpt4 book ai didi

MySQL 计算过选择不适用于空子选择

转载 作者:可可西里 更新时间:2023-11-01 08:50:14 26 4
gpt4 key购买 nike

我试图通过一个 SQL 查询来获取 5 个不同表中结果的总和。我有 5 个表,每个表可能包含属于订单的记录。 5 个表中所有记录的总和决定了总订单价格。

在这个论坛上搜索我提出了以下查询:

SELECT
OrderTotal.total + Shipping.amount + Service.amount - Gift.amount - RMA.total as TotalCosts
FROM
(SELECT SUM(price * amount) AS total FROM order WHERE order_id=123456) OrderTotal
(SELECT amount FROM shipping WHERE order_id=123456) Shipping,
(SELECT amount FROM service WHERE order_id=123456) Service,
(SELECT SUM(price * amount) AS total FROM rma WHERE order_id=123456) RMA,
(SELECT amount FROM gift WHERE order_id=123456) Gift

我现在面临的问题是,例如当最后一个 SELECT 返回 0 行时,总的 TotalCosts 没有返回。

如何解决?

最佳答案

使用 UNION 怎么样?

SELECT  order_id, SUM(total) GrandTotal
FROM
(
SELECT order_id, SUM(price * amount) AS total
FROM `order`
WHERE order_id = 123456
UNION ALL
SELECT order_id, amount AS total
FROM shipping
WHERE order_id = 123456
UNION ALL
SELECT order_id, amount AS total
FROM service
WHERE order_id = 123456
UNION ALL
SELECT order_id, SUM(price * amount) AS total
FROM rma
WHERE order_id = 123456
UNION ALL
SELECT order_id, amount AS total
FROM gift
WHERE order_id=123456
) subTable
GROUP BY order_id

关于MySQL 计算过选择不适用于空子选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15343025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com