gpt4 book ai didi

mysql - 使用 UNION 对 SELECT COUNT 语句中的表进行 SUM 查询

转载 作者:行者123 更新时间:2023-11-29 10:44:50 30 4
gpt4 key购买 nike

我目前正在尝试对 MySQL 语句的结果进行求和,该语句给出了几个不同表的行数。

我已经研究了 stackoverflow 中与此问题相关的所有解决方案。不幸的是,我无法找出适合我的情况的正确语法。

我的工作陈述以及总结的结果:

SET @shipmentId=456;
SELECT
(SELECT COUNT(*) FROM Table1 WHERE ShipmentID = @shipmentId)
UNION ALL
(SELECT COUNT(*) FROM Table2 WHERE ShipmentID = @shipmentId)
UNION ALL
(SELECT COUNT(*) FROM Table3 WHERE ShipmentID = @shipmentId)
UNION ALL
(SELECT COUNT(*)FROM Table4 WHERE ShipmentID = @shipmentId)
UNION ALL
(SELECT COUNT(*)FROM Table5 WHERE ShipmentID = @shipmentId);

在我看来,这应该是最接近正确的解决方案,但我不确定(尝试了很多变体):

SET @shipmentId=456;
SELECT SUM(MeasuredValues) FROM
SELECT(
(SELECT COUNT(*) FROM Table1 WHERE ShipmentID = @shipmentId) AS MeasuredValues
UNION ALL
(SELECT COUNT(*) FROM Table2 WHERE ShipmentID = @shipmentId) AS MeasuredValues
UNION ALL
(SELECT COUNT(*) FROM Table3 WHERE ShipmentID = @shipmentId) AS MeasuredValues
UNION ALL
(SELECT COUNT(*)FROM Table4 WHERE ShipmentID = @shipmentId) AS MeasuredValues
UNION ALL
(SELECT COUNT(*)FROM Table5 WHERE ShipmentID = @shipmentId) AS MeasuredValues) t1;

预先感谢您的帮助。

已经尝试过以下链接: StackOverFlow Solution1

StackOverFlow Solution2

最佳答案

您可以简单地总结您的选择:

SET @shipmentId=456;
SELECT
(SELECT COUNT(*) FROM Table1 WHERE ShipmentID = @shipmentId)
+
(SELECT COUNT(*) FROM Table2 WHERE ShipmentID = @shipmentId)
+
(SELECT COUNT(*) FROM Table3 WHERE ShipmentID = @shipmentId)
+
(SELECT COUNT(*) FROM Table4 WHERE ShipmentID = @shipmentId)
+
(SELECT COUNT(*) FROM Table5 WHERE ShipmentID = @shipmentId);

关于mysql - 使用 UNION 对 SELECT COUNT 语句中的表进行 SUM 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790587/

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