我有两张 table
table1
|---------------------|------------------|------------------|
| student_id | studentname | parentid |
|---------------------|------------------|------------------|
| 1 | Kobe | 1 |
|---------------------|------------------|------------------|
|---------------------|------------------|------------------|
| 2 | Lebron | 1 |
|---------------------|------------------|------------------|
table2
|---------------------|------------------|
| parentid | parentname |
|---------------------|------------------|
| 1 | Jordan |
|---------------------|------------------|
我想选择这样的输出
result
|---------------------|------------------|------------------|----------------
--
| parentid | parentname | childrenid | childrenname
|---------------------|------------------|------------------|------------------
| 1 | Jordan | 1,2 | Kobe,Jordan
|---------------------|------------------|------------------|------------------
这可能发生吗?预先感谢我已经使用了这个查询,但行是重复的
select * from table2 left join table1 ON table1.parentid = table2.parentid
最佳答案
在mysql中使用GROUP_CONCAT
函数
select parentname,
GROUP_CONCAT(student_id SEPARATOR ',') AS childrenid,
GROUP_CONCAT(studentname SEPARATOR ',') childrenname
from table2 p left join table1 s on
p.parentid=s.parentid
group by parentname
parentname childrenid childrenname
Jordan 1,2 Kobe,Lebron
关于mysql - 将其他表中的多行合并到mysql中的1列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691532/