在做了一些连接和填充后,我有以下格式的表格
name session_id status
abc 1 null
xyz 2 11
jack 2 10
zuck 1 10
paul 1 10
我希望我的结果能够像这样分组
session_id name+status
1 abc:-1, zuck:10, paul:10
2 xyz:11, jack:11
所以我在sql中使用了MySql group_concat,如
SELECT sr.avail_id AS id,sr.student_id, sa1.punctuality_status as associate_punctuality_status, IF(
(sa.punctuality_status IS NULL),
(group_concat(u.firstname, ' ', u.lastname, ':', '-1'),
(group_concat(u.firstname, ' ', u.lastname, ':', sa.punctuality_status)
),
sr.tutor_id AS associate_id, FROM_UNIXTIME( sr.timestart ) AS timestart,
sr.session_id AS session_id, sr.type AS session_type, p.name AS program_name,
m.name AS module_name, ms.name AS session_name, sr.status as session_status FROM mdl_session_requests AS sr
LEFT JOIN mdl_session_attendee AS sa ON ( sr.student_id = sa.user_id AND sr.session_id = sa.session_id )
LEFT JOIN mdl_session_attendee AS sa1 ON (sr.tutor_id=sa1.user_id and sr.session_id=sa1.session_id)
INNER JOIN mdl_module_session ms ON ms.id = sr.course_id
INNER JOIN mdl_module m ON m.id = ms.module_id
INNER JOIN mdl_program p ON p.id = m.program_id
INNER JOIN mdl_user u ON u.id = sr.student_id
WHERE sr.tutor_id =438 group by avail_id order by sr.timestart desc
error =“#1064 - 您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在'AS associate_id,FROM_UNIXTIME(sr.timestart)AS timestart,sr附近使用正确的语法。 session_id AS'在第6行“
这个sql有问题吗?
答案 0 :(得分:2)
SELECT
s.session_id AS id,
group_concat(SEPARATOR ', ' CONCAT(u.firstname, ' ', u.lastname, ':',IF(s1.status IS NULL,'-1',s1.status))), sr.tutor_id
FROM [a table]
GROUP BY session_id
问题:
GROUP_CONCAT
可以在一个字段上完成,因此您需要先CONCAT()
所有值。