我是mysql
的新手。
我有一个查询来从不同的表中获取计数,它可以正常工作。但是,现在我想将所有3个查询COUNT分成1个,如SUM(COUNT1,COUNT2,COUNT3)
select COUNT(*) as count1, 0 as count2, 0 as count3 from table1
UNION ALL
select 0 as count1, COUNT(*) as count2, 0 as count3 from table2
UNION ALL
select 0 as count1, 0 as count2, COUNT(*) as count3 from table3
E.g。 count1 = 10,count2 = 20,count3 = 15
然后,我想得到sum = 45
答案 0 :(得分:4)
您可以将SUM()
放入子查询中,然后SELECT SUM(count) AS total
FROM (
SELECT COUNT(*) AS count FROM table1
UNION ALL
SELECT COUNT(*) AS count FROM table2
UNION ALL
SELECT COUNT(*) AS count FROM table3
) AS subquery
计数。但是没有必要将它们放在每个联合查询的单独列中。
{{1}}
答案 1 :(得分:3)
要从表中获取所有计数的总和,您可以将查询编写为
select
(select COUNT(*) from table1) +
(select COUNT(*) from table2) +
(select COUNT(*) from table3) as total
按照您的方法,您可以将unioined查询包装为子选择,然后对结果应用总和
SELECT SUM(count1) + SUM(count2) + SUM(count3) total
FROM (
SELECT COUNT(*) AS count1, 0 AS count2, 0 AS count3 FROM table1
UNION ALL
SELECT 0 AS count1, COUNT(*) AS count2, 0 AS count3 FROM table2
UNION ALL
SELECT 0 AS count1, 0 AS count2, COUNT(*) AS count3 FROM table3
) t