Mysql

如何在一個查詢中進行多個計數?

  • March 13, 2017

我計算帶有查詢的記錄,例如

SELECT COUNT(col1) FROM table1 WHERE col1 LIKE '%something%'
SELECT COUNT(col1) FROM table1 WHERE col1 LIKE '%another%'
SELECT COUNT(col1) FROM table1 WHERE col1 LIKE '%word%'

對於每個計數,mysql 需要遍歷整個表,如果表很長,查詢很多,這是一個大問題。

我想知道是否有一種方法可以在一個查詢中計算所有計數。在這種情況下,當mysql遍歷每一行時,它會處理所有的計數,不需要一遍又一遍地掃描整個表。

要計算每個您可以嘗試的計數

SELECT
   COUNT(CASE WHEN `col1` LIKE '%something%' THEN 1 END) AS count1,
   COUNT(CASE WHEN `col1` LIKE '%another%' THEN 1 END) AS count2,
   COUNT(CASE WHEN `col1` LIKE '%word%' THEN 1 END) AS count3
FROM `table1`; 

類似於 Aaron 的解決方案,更短的語法:

SELECT
   SUM(col1 LIKE '%something%') AS count1,
   SUM(col1 LIKE '%another%') AS count2,
   SUM(col1 LIKE '%word%') AS count3
FROM `table1`

LIKE 表達式產生一個布爾結果。TRUE1FALSE0,所以CASE這裡是多餘的。

引用自:https://dba.stackexchange.com/questions/23068