2012-08-23 222 views
3

因此,這裏的SQL我有GROUP_CONCAT select語句

SELECT c.name AS 'name', 
    COUNT(sc.condition_id) AS 'conditions_count' 
FROM reviews r, strain_conditions sc 
LEFT JOIN conditions c ON sc.condition_id = c.id 
WHERE sc.strain_id = 1 && sc.review_id = r.id && r.moderated = 1 
GROUP BY sc.condition_id 
ORDER BY conditions_count DESC 
LIMIT 3; 

它返回

+---------------+------------------+ 
| name   | conditions_count | 
+---------------+------------------+ 
| Fiber Myalgia |    2 | 
| Anxiety  |    2 | 
| ADHD   |    1 | 
+---------------+------------------+ 

我需要做的是GROUP_CONCAT名字結果讓我最終的結果是根本

「纖維肌痛,焦慮,多動症「

+0

你想讓他們出現在任何特定的順序或不關係呢? –

回答

3

將它包裝在子查詢中。試試這個,

SELECT GROUP_CONCAT(f.name) as `name` 
FROM 
(
    SELECT c.name AS 'name', 
      COUNT(sc.condition_id) AS 'conditions_count' 
    FROM reviews r, strain_conditions sc 
    LEFT JOIN conditions c ON sc.condition_id = c.id 
    WHERE sc.strain_id = 1 && sc.review_id = r.id && r.moderated = 1 
    GROUP BY sc.condition_id 
    ORDER BY conditions_count DESC 
    LIMIT 3 
) f 
3

您需要嵌套選擇,因爲LIMIT應該只適用於子查詢。

SELECT GROUP_CONCAT(name) AS name 
FROM 
(
    SELECT c.name AS name 
    FROM reviews r, strain_conditions sc 
    LEFT JOIN conditions c ON sc.condition_id = c.id 
    WHERE sc.strain_id = 1 && sc.review_id = r.id && r.moderated = 1 
    GROUP BY sc.condition_id 
    ORDER BY conditions_count DESC 
    LIMIT 3 
) AS T1 

如果你希望他們通過遞減計數命令你應該添加一個ORDER BYGROUP_CONCAT

SELECT GROUP_CONCAT(name ORDER BY conditions_count DESC) AS name 
FROM 
(
    -- your query here 
) AS T1 

如果你也想逗號後的空間,使用SEPARATOR

SELECT GROUP_CONCAT(name ORDER BY conditions_count DESC SEPARATOR ', ') AS name 
FROM 
(
    -- your query here 
) AS T1 

有關詳細信息,請參閱手冊頁GROUP_CONCAT

+0

@ypercube:好點。修正了,謝謝。 –

1

你需要的地方,在一個子選擇:

SELECT GROUP_CONCAT(name) AS name 
FROM 
(
    SELECT c.name AS 'name', 
    COUNT(sc.condition_id) AS 'conditions_count' 
    FROM reviews r, strain_conditions sc 
    LEFT JOIN conditions c ON sc.condition_id = c.id 
    WHERE sc.strain_id = 1 && sc.review_id = r.id && r.moderated = 1 
    GROUP BY sc.condition_id 
    ORDER BY conditions_count DESC 
    LIMIT 3 
) x