Mysql 一行中有两个结果,其中包含两列和组
我试图在一行上混合多个结果 以下是数据示例:Mysql 一行中有两个结果,其中包含两列和组,mysql,sql,Mysql,Sql,我试图在一行上混合多个结果 以下是数据示例: TOPICS topicID state title 1 A 'Hello' 1 B 'Bye' 2 A 'Great' 并与: STUDENTS topicID studentID 1 23 1 27 2
TOPICS
topicID state title
1 A 'Hello'
1 B 'Bye'
2 A 'Great'
并与:
STUDENTS
topicID studentID
1 23
1 27
2 33
2 40
我想要这个结果:
Topic A B Students
1 'Hello' 'Bye' 23,27
2 'Great' null 33,40
现在我在SELECT中使用组_CONCAT(不同的studentID分隔符“,”)正确地接收用户,但我不能再次使用它。我已尝试了CASE,但未成功。您可以使用条件聚合和相关子查询:
select t.topicid,
max(case when t.state = 'A' then t.title end) as a,
max(case when t.state = 'B' then t.title end) as b,
(select group_concat(s.studentid)
from students s
where s.topicid = t.topicid
) as students
from topics t
group by topicid;
相关子查询消除了对
group\u-concat(distinct)
的需要,这比仅使用group\u-concat()更昂贵。
考虑处理应用程序代码中的数据显示问题