将行值添加到单个列MYSQL中

时间:2016-02-01 17:52:36

标签: mysql mysql-5.6

我有这些数据。

 create table student
(
   student_id int,
   name varchar(50)
 )

 create table student_option
(
   student_option_id int, 
   student_id int,
   s_option  varchar(50)
 )  
 insert into student
(
student_id,
name
)values(1,'John'),(2,'Martin')

insert into student_option
(
  student_option_id,
  student_id,
  s_option
  )values(1,1,'A'),(2,1,'B'),(3,2,'C'),(4,2,'D')

select * from student 
select * from student_option

我希望输出显示为

  student_name     options
    John             A, B
    Martin           C, D

在MYSQL5.6中最优化的方法是什么

提前致谢

1 个答案:

答案 0 :(得分:0)

这个应该有效。你基本上使用GROUP_CONCAT function from MySQL和GROUP BY名称。

select s.name, group_concat(o.s_option) 
  from student s 
  left join student_option o on (s.student_id = o.student_id) 
  group by s.name;

结果:

name    s_option

John    B,A    
Martin  D,C