2012-03-17 63 views
2

我想搜索多個變量,在WHERE條件下或在HAVING條件下,在group_concat表中可能爲true。事情是這樣的:如何在WHERE條件或HAVING條件下搜索可返回true的值?

SELECT 
    article.id, 
    article.name, 
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags, 
    GROUP_CONCAT(tags.id order by tags.id) AS idTags 
FROM 
    article 
    LEFT JOIN .... 
    LEFT JOIN .... 
WHERE article.name LIKE '%var1%' OR HAVING nameTags LIKE '%var1%' AND 
WHERE article.name LIKE '%var2%' OR HAVING nameTags LIKE '%var2%' 
GROUP BY id 

有一些可能的方式還是好做2個querys?

這個查詢:

SELECT 
    article.id, 
    article.name, 
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags, 
    GROUP_CONCAT(tags.id order by tags.id) AS idTags 
FROM 
    article 
    LEFT JOIN .... 
    LEFT JOIN .... 
WHERE 
(article.name LIKE '%var1%' OR tags.name LIKE '%var1%') AND 
(article.name LIKE '%var2%' OR tags.name LIKE '%var2%') 
GROUP BY id 

找到我尋找,但我必須做第二次查詢,顯示結果我想要的。

對不起,如果問題重複,我不知道該怎麼去問,所以我不知道如何去搜索它。對不起我的英文!

回答

0
SELECT 
    article.id, 
    article.name, 
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags, 
    GROUP_CONCAT(tags.id order by tags.id) AS idTags, 
    MAX(IF(article.name LIKE '%var1%',1,0)) AS var1match, 
    MAX(IF(article.name LIKE '%var2%',1,0)) AS var2match 
FROM 
    article 
    LEFT JOIN .... 
    LEFT JOIN .... 
GROUP BY id 
HAVING 
    (nameTags LIKE '%var1%' OR var1match=1) 
    OR (nameTags LIKE '%var2%' OR var2match=1) 
+0

它完美的作品!不知道這個功能!我會學習以便理解它! 我還不能給你點數,抱歉,並且非常感謝! – Leo 2012-03-17 21:05:23

+0

只需要在MAX之間加上逗號 – Leo 2012-03-17 21:17:08

+0

感謝您的糾正,編輯我的答案 – 2012-03-17 22:39:12