2011-07-28 35 views
0

提前半新現象:我需要做兩個選擇並計算它們兩個中的項目數量。這裏是什麼,我想會的工作了一個壞榜樣 -如何計算兩個選擇中的條目數量?

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()中會讓我得到我想要的東西,但它會拋出一個語法錯誤。正確的事情可能是微不足道的,但我只是d看不到它。有什麼想法嗎?謝謝!

回答

-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 
+0

我我想知道downvote的原因。他的例子不需要子查詢。 –

+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 
+0

對 - 吉姆,這裏的重點在於,當你把它放在你所在的位置時,MySQL不知道你所指的是什麼。如果你選擇了'SELECT',它會更快樂,因爲它知道你想要真正看到總和! –

+0

我投票贊成,因爲這幾乎就是我的想法,但我認爲如果兩個計數相同,你需要將它變成「全部工會」。 – Hoons

+0

感謝您指出錯誤@Hoons – Jacob