我必须在一个简单的查询中使用SELECT,UNIONed ...
SELECT description_x, a, b, c, d from table a WHERE person_id = 1 UNION SELECT description_y, e ,f ,g ,h from table b WHERE person_id = 1
... a,b,c,d,e,f,g,h都是整数。我如何理解它们,结果看起来像这样...
row 1: description_x | a | b | c | d row 2: description_y | e | f | g | h row 3: summary | a+e | b+f | c+g | d+h
...好吗?
非常感谢!
答案 0 :(得分:2)
您可以向其添加另一个union
来进行聚合。
select description_x, a, b, c, d from table a where person_id = 1
union all
select description_y, e ,f ,g ,h from table b where person_id = 1
union all
select 'summary', sum(a), sum(b), sum(c), sum(d) from (
select a, b, c, d from table a where person_id = 1
union all
select e ,f ,g ,h from table b where person_id = 1
) t
如果MySQL支持的CTE(正如评论中提到的那样,将在MySQL 8之后推出),我们不需要再次重写相同的查询。
答案 1 :(得分:0)
select sum(a) as a,sum(b) as b,sum(c) as c,sum(d) as d from (
SELECT description_x, a, b, c, d from table a WHERE person_id = 1
UNION All
SELECT description_y, e ,f ,g ,h from table b WHERE person_id = 1
)T