2017-03-06 23 views
1

給定一個MySQL查詢像這樣的選擇計數:LIKE方面

SELECT COUNT(*) FROM questions 
WHERE questions.text LIKE "%some word%" 
OR questions.text LIKE "%another word%" 
OR questions.text LIKE "%yet another word%" 
AND questions.field = "test" 
... more WHERE conditions 

什麼是返回擊穿每個LIKE來看,而不是對應於全部三個LIKE語句行的最好方法?

我知道這是可能通過使每個LIKE項的分離SELECT聲明這樣做,但有可能是一個有點短任何方式來包裝這個成一個SELECT聲明,還是什麼?

回答

1

你可以使用一個選擇的情況下匹配值的總和時

SELECT 
    sum(case when questions.text LIKE "%some word%" then 1 else 0 end) as test1 
    , sum(case when questions.text LIKE "%another word%" then 1 else 0 end) as test2 
    , sum(case when questions.text LIKE "%yet another word%" then 1 else 0 end) as test3 
WHERE questions.field = "test" 
... more WHERE conditions