我是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
例如。 count1 = 10,count2 = 20和count3 = 15
然后,我想求和= 45
最佳答案
您可以将UNION
放在子查询中,然后将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
关于mysql - 如何计算所有COUNT的总和?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47975437/