gpt4 book ai didi

mysql - 如何用MySQL编写多表查询?

转载 作者:行者123 更新时间:2023-11-29 15:43:48 25 4
gpt4 key购买 nike

我有两张 table 消费和充值。我怎样才能得到结果?

消费表

user_name   date                consume 
a 12/12/2018 12:20 10
a 12/12/2018 12:20 12
a 1/1/2019 11:00 13

充值表

user_name   date                recharge    
a 12/12/2018 12:20 20
a 12/12/2018 12:20 30
a 1/1/2019 11:00 40

结果

user_name   date                  consume   recharge
a 12/12/2018 12:20 22 50
a 1/4/2019 12:20 13 40

最佳答案

如果列数匹配并且数据类型兼容,我们可以使用 UNION ALL 集合运算符来组合两个集合

 SELECT c.user_name
, c.date
, c.consume
, 0 AS recharge
FROM consume c
UNION ALL
SELECT r.user_name
, r.date
, 0 AS consume
, r.recharge
FROM recharge r

我们可以将其包装在括号中,并像外部查询中的表一样引用它。

外部查询可以执行 GROUP BY 操作将行折叠为组,并且我们可以使用 SUM 聚合函数对值进行总计。

类似这样的事情:

SELECT t.user_name 
, t.date
, SUM(t.consume) AS consume
, SUM(t.recharge) AS recharge
FROM ( -- inline view
SELECT c.user_name
, c.date
, c.consume
, 0 AS recharge
FROM consume c
UNION ALL
SELECT r.user_name
, r.date
, 0 AS consume
, r.recharge
FROM recharge r
) t
GROUP
BY t.user_name
, t.date

这对于大小合理的集合是可行的。对于大量行, itgerlarge

还有其他可能的查询模式。这里展示的方法对于简单的集合和一些合理大小的集合是可行的。我们遇到了 Hugh-Jass 集的一些性能问题。

为了澄清规范...如果 recharge 中有行而 consume 中没有匹配的行,我们要返回什么?反之亦然?我们要省略这些行还是包含它们?

关于mysql - 如何用MySQL编写多表查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299989/

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