未来的半新生:我需要做两次选择并计算两者中的项目数。这是我认为可行的一个不好的例子 -
sum(
select count(*) as count1 from users where name = 'John'
union
select count(*) as count1 from users where name = 'Mary'
) as theCount
(正如我所说的那样,这是一个不好的例子,因为我显然可以将它写成带有适当WHERE子句的单个选择。在我真正需要做的事情中,我要做的两件事就是这样我不能将它们作为单个选择(或者,至少,我还没有找到一种方法将它们作为单个选择)。
无论如何,我认为我要做的是明确的:select-union-select位返回一个包含两个选择的计数的列;那部分工作正常。我认为将它们包装在SUM()中会得到我想要的东西,但它会引发语法错误。正确的事情可能是微不足道的,但我只是没有看到它。有什么想法吗?谢谢!
答案 0 :(得分:2)
对于通用选择,您不一定要用以下内容编写:
SELECT sum(count1) as totalcount FROM (
select count(*) as count1 from users where name = 'John'
union all
select count(*) as count1 from users where name = 'Mary'
) as theCount
答案 1 :(得分:-1)
select count(*) as count1 from users where name in ('John','Mary')
这是另一种选择
select ( select count(*) as count1 from users where name = 'John')
+
( select count(*) as count1 from users where name = 'Mary') as total
另一种可能的解决方案:
select
sum(if(name='John',1,0)) as tot_John,
sum(if(name='Mary',1,0)) as tot_Mary,
sum(if(name in ('John','Mary'),1,0)) as total
from users