所以这是我的SQL
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)
您需要嵌套选择,因为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 BY
添加GROUP_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
的手册页。
答案 1 :(得分: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
答案 2 :(得分: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