2011-12-07 56 views
2

我有一組文章。其中一些文章已被分配x個標籤。MySQL:可選建立組Concat字段

我想選擇SELECT中指定格式的所有文章,並且如果文章還有任何數量的標籤分配,請將它們放入單個GROUP_CONCAT字段中。

下面的SQL做我需要的一切,除了只檢索至少有一個標籤文章。

我該如何使標記要求是可選的?

SELECT d.entry_id AS entry_id 
    , d.field_id_40 AS body 
    , t.title AS title 
    , t.url_title AS url_title 
    , t.entry_date AS entry_date 
    , GROUP_CONCAT(g.tag_name ORDER BY g.tag_name) AS tag 
FROM exp_channel_data d 
    , exp_category_posts c 
    , exp_channel_titles t 
    , exp_tagger_links l 
    , exp_tagger g 
WHERE t.YEAR > '2005' 
    AND t.site_id = d.site_id 
    AND d.site_id = 9 
    AND (c.cat_id = 95 
     OR c.cat_id = 93 
     OR c.cat_id = 64 
     OR c.cat_id = 24 
    ) 
    AND d.entry_id = t.entry_id 
    AND t.entry_id = c.entry_id 
    AND t.STATUS = 'open' 
    AND l.tag_id = g.tag_id 
    AND d.entry_id = l.entry_id 
GROUP BY d.entry_id 
+3

使用'JOIN',不'WHERE',爲您的加盟表。然後,將'INNER JOIN'改爲'LEFT JOIN'可以很容易地解決你的問題。 –

回答

3

將您的JOINS切換爲使用JOIN語法,這應該爲您提供答案。

SELECT d.entry_id AS entry_id 
    , d.field_id_40 AS body 
    , t.title AS title 
    , t.url_title AS url_title 
    , t.entry_date AS entry_date 
    , GROUP_CONCAT(g.tag_name ORDER BY g.tag_name) AS tag 
FROM exp_channel_data AS d 
INNER JOIN exp_channel_titles AS t ON d.site_id = t.site_id 
    AND d.entry_id = t.entry_id 
INNER JOIN exp_category_posts AS c ON t.entry_id = c.entry_id 
LEFT OUTER JOIN exp_tagger_links AS l ON d.entry_id = l.entry_id 
LEFT OUTER JOIN exp_tagger AS g ON l.tag_id = g.tag_id 
WHERE t.YEAR > '2005' 
    AND d.site_id = 9 
    AND c.cat_id IN (95, 93, 64, 24) 
    AND t.STATUS = 'open' 
GROUP BY d.entry_id 

您可能也想看看A visual explanation of SQL joins.