开发者

How to count the number of entries in two selects?

Semi-newbyism ahead: I need to do two selects and count the number of items in both of them. Here's a bad example of what I thought would work --

sum(
  select count(*) as count1 from users where name = 'John'
    union
  select count(*) as count1 from users where name = 'Mary'
) as theCount

(This is, as I said, a BAD example, since I could obviously write this as a single select with an appropriate WHERE clause. In what I really have to do, the two things I have to do are such that I can't do them as a single select (or, at least, I haven't yet found a way to do them as a single select).

Anyway, I think what I'm trying to do is clear: the select-union-select bit return开发者_C百科s a column containing the counts of the two selects; that part works fine. I thought that wrapping them in a SUM() would get me what I wanted, but it's throwing a syntax error. The right thing is probably trivial, but I just don't see it. Any thoughts out there? Thanks!


For generic selects that you can't necessarily write with one where:

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


select count(*) as count1 from users where name in ('John','Mary')

This is another alternative

select ( select count(*) as count1 from users where name = 'John')
+
( select count(*) as count1 from users where name = 'Mary') as total

Another possible solution:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜