2012-03-19 92 views
2

我知道這有一個愚蠢的解決方案,但是,對不起,我有點困惑。MySQL總結了兩條COUNT語句

我有兩個SELECT COUNT語句。例如:

聲明1

SELECT COUNT(softwareone) AS totalcount 
FROM my_table WHERE softwareone LIKE '%typeone%' 

TOTALCOUNT = 3 _

聲明2

SELECT COUNT(softwaretwo) AS totalcount 
FROM my_table WHERE softwaretwo LIKE '%typeone%' 

totalcout = 1

我想總計兩個總數以獲得totalcount = 4.有一種方法可以做到這一點?

注意:「softwareone」和「softwaretwo」列中的軟件類型是相同類型(相同的值)。

感謝所有。

+1

是故意的,這兩個選擇對'%typeone%'過濾器? – 2012-03-19 18:37:07

回答

4

一種方法是這樣寫:

SELECT SUM(CASE WHEN softwareone LIKE '%typeone%' 
       AND softwaretwo LIKE '%typeone%' 
       THEN 2 
       ELSE 1 
      END 
     ) AS "totalcount" 
    FROM my_table 
WHERE softwareone LIKE '%typeone%' 
    OR softwaretwo LIKE '%typeone%' 
; 

當滿足兩個條件(因此,如果softwareonesoftwaretwo都是LIKE '%typeone%',則行計數兩次)的CASE ... END表達式會2,並1時其中只有一個是。因此,SUM(CASE ... END)給出滿足一個條件的總行數加上滿足其他條件的總行數。

+2

+1子查詢解決方案會導致MySQL多次掃描記錄。這個查詢只會導致MySQL掃描一次。 – 2012-03-19 18:55:14

3

你可以使用一個

Select l1.totalcount + l2.totalcount FROM 
(SELECT COUNT(softwareone) AS totalcount 
FROM my_table WHERE softwareone LIKE '%typeone%') as l1, 
(SELECT COUNT(softwaretwo) AS totalcount 
FROM my_table WHERE softwaretwo LIKE '%typeone%') as l2