3

So here's the SQL I have

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;

Which returns

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

What I need to do is GROUP_CONCAT the name results so my end result is simply

"Fiber Myalgia, Anxiety, ADHD"

4

3 回答 3

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

于 2012-08-23T23:22:01.637 回答
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
于 2012-08-23T23:22:41.373 回答
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
于 2012-08-23T23:22:46.870 回答