mysql - 在 group_concat 中包含空结果

标签 mysql group-concat isnull ifnull

我有两个这样的表

profile_answers

+---------+------------+
|      id | class_name |
+---------+------------+
|       1 | Class 1    |
|       2 | Class 2    |
|       3 | Class 1    |
+---------+------------+

教育

+---------+--------------------+------------+
|      id | profile_answers_id |  sample    |
+---------+--------------------+------------+
|       1 | 1                  |     1234   |
|       2 | 1                  |     2334   |
|       3 | 1                  |     3434   |
+---------+------------+--------------------+

我运行了查询,

select educations.profile_answer_id, GROUP_CONCAT(educations.sample) from educations
LEFT JOIN profile_answers ON educations.profile_answers_id = profile_answers.id

我得到了

+--------+--------------------+-------------+
|      id | sample                          | 
+---------+--------------------+------------+
|       1 | 1234,2334,3434                  |
+---------+------------+--------------------+

我其实想要,

+--------+--------------------+-------------+
|      id | sample                          | 
+---------+--------------------+------------+
|       1 | 1234,2334,3434                  |
|       2 | NULL                            |
|       3 | NULL                            |  
+---------+------------+--------------------+

最佳答案

SELECT id,IFNULL(samples,'NULL') sample FROM 
(
    SELECT
        AA.id,
        GROUP_CONCAT(DISTINCT BB.sample) samples
    FROM
        profile_answers AA LEFT JOIN educations BB
        ON AA.id = BB.profile_answers_id
    GROUP BY AA.id
) A;

关于mysql - 在 group_concat 中包含空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820298/

相关文章:

mysql - 在 Rails ActiveRecord 中,为什么我的 JOINed 表中的列之一抛出错误消息?

多行的MySQL AVG TimeDiff

mysql - SQL 多连接分组

php - 在 GROUP_CONCAT() 中附加 <a href></a>

mysql - 按 count(*) 和 0 而不是空分组

mysql - 查找薪资表中缺失的员工

mysql - 应该使用什么数据库结构来包含多个类别中的表行?

MYSQL 按兼容性分组产品

sql - 如何在 sql 选择查询中将 "0"显示为默认值而不是 "Null"

tsql - ISNULL(Count(x),0) null 时不返回 0