繁体   English   中英

GROUP_CONCAT一个select语句

[英]GROUP_CONCAT a select statement

所以这是我的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名称的结果,所以我的最终结果很简单

“纤维肌痛,焦虑,多动症”

您需要嵌套选择,因为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

如果您希望按递减计数排序,则应该向GROUP_CONCAT添加ORDER BY

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的手册页。

将其包装在子查询中。 试试这个,

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

您需要将其放在子选择中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM