将行值添加到单列MYSQL中

将行值添加到单列MYSQL中

This question already has answers here:
comma separated string of selected values in mysql
                                
                                    (7个答案)
                                
                        
                                4年前关闭。
            
                    
我有这个数据。

 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中最优化的方法是什么

提前致谢

最佳答案

这应该工作。之后,您基本上使用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

关于mysql - 将行值添加到单列MYSQL中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35137112/

10-13 04:31