mysql - GROUP_CONCAT 一条选择语句

标签 mysql sql database

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

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

最佳答案

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

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

关于mysql - GROUP_CONCAT 一条选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12101298/

相关文章:

mysql - 列显示在mysql中

php - 创建数组后用逗号将数组添加到 mysql varchar 行中

SQL Server : copy data from one column to another column?

php - 使用 PHP 将字符串插入 MySQL 表和 HTML 页面的安全性

java - where子句中的未知列错误,使用MySQL和Java

sql - XML 解析错误 : 'A string literal was expected' when inserting values into table

php - 如何缩短一个sql查询

php - 从数据库动态加载元素

c# - 如何在 C# 中更新数据源

ruby-on-rails - Rails 中的多个数据库