gpt4 book ai didi

mysql查询从两组不同的表中各选择两列

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:59 25 4
gpt4 key购买 nike

需要从两组不同的表中各选择两列。

现在我有两个不同的查询,但想知道是否有办法在一个查询中使用它

查询-1

 SELECT     
BSM, DATE, HOUR, SUM(t.ATT), SUM(t.AVG_HLD)
FROM (
SELECT BSM, DATE, HOUR, ATT, AVG_HLD FROM t1 WHERE ".$whereCondition." UNION ALL
SELECT BSM, DATE, HOUR, ATT, AVG_HLD FROM t2 WHERE ".$whereCondition."
) t
GROUP BY BSM, DATE, HOUR ";

查询 2

 SELECT     
BSM, DATE, HOUR, SUM(s.M_ATT), SUM(s.M_AVG_HLD)
FROM (
SELECT BSM, DATE, HOUR, M_ATT, AVG_HLD FROM t3 WHERE ".$whereCondition." UNION ALL
SELECT BSM, DATE, HOUR, M_ATT, AVG_HLD FROM t4 WHERE ".$whereCondition."
) s
GROUP BY BSM, DATE, HOUR ";

如何将 Query-1 和 Query-2 结合起来......

 SELECT     
BSM, DATE, HOUR, SUM(s.ATT), SUM(s.AVG_HLD), SUM(s.M_ATT), SUM(s.M_AVG_HLD)
FROM (
** Whatever it is **
)
GROUP BY BSM, DATE, HOUR ";

最佳答案

对所有 4 个子查询创建一个 UNION,为来自另一对表的列插入 0 列。

SELECT BSM, DATE, HOUR, SUM(ATT) AS ATT, SUM(AVG_HLD) AS AVG_HLD, SUM(M_ATT) AS M_ATT, SUM(M_AVG_HLD) AS M_AVG_HLD
FROM (
SELECT BSM, DATE, HOUR, ATT, AVG_HLD, 0 AS M_ATT, 0 AS M_AVG_HLD FROM t1 WHERE ".$whereCondition."
UNION ALL
SELECT BSM, DATE, HOUR, ATT, AVG_HLD, 0 AS M_ATT, 0 AS M_AVG_HLD FROM t2 WHERE ".$whereCondition."
UNION ALL
SELECT BSM, DATE, HOUR, 0 AS ATT, 0 AS AVG_HLD, M_ATT, M_AVG_HLD FROM t3 WHERE ".$whereCondition."
UNION ALL
SELECT BSM, DATE, HOUR, 0 AS ATT, 0 AS AVG_HLD, M_ATT, M_AVG_HLD FROM t4 WHERE ".$whereCondition."
) u
GROUP BY BSM, DATE, HOUR

关于mysql查询从两组不同的表中各选择两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713225/

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