结合两个表mysql

时间:2015-01-30 18:44:59

标签: mysql

是否可以像这样组合这两个表?来自table2的所有主题应该从table1组合,并且主题应该与table1中的相同ID排成一行。

Table1 
----------------------
ID   Student_ID   Name

 1   200000      Paul

 2   202907      Ger


Table2
----------------------
Student_ID   Subject

200000       ACT111

200000       ACT112

200000       ACT113

202907       ACT111

-------------------


Expected Combination
------------------------------------------------------
ID       Student_ID     Name            Subject
1        200000         Paul      ACT111 ACT112 ACT113  

2 个答案:

答案 0 :(得分:1)

您必须关联表格才能获取数据(请参阅JOIN syntax),然后您可以使用group_concat()获取以逗号分隔的值列表:

select t1.id, t1.student_id, t1.name
     , group_concat(t2.subject separator ',') as subjects
from table1 as t1
     inner join table2 as t2 on t1.student_id = t2.student_id
--   ^^^^^^^^^^ Replace 'INNER JOIN' with 'LEFT JOIN' if you want to
--              also show the students with no subjects
group by t1.id;

答案 1 :(得分:0)

只需使用简单的JOIN(或LEFT JOIN,如果您希望Table2Table1中的条目没有条目,则GROUP_CONCAT功能:

SELECT t1.ID, t1.Student_ID, t1.Name, GROUP_CONCAT(DISTINCT t2.Subject SEPARATOR ' ') as Subject
FROM Table1 t1 
JOIN Table2 t2 ON t1.Student_ID = t2.Student_ID
GROUP BY t1.Student_ID

这将从Table1中获取行,并从Table2中添加具有相同Student_ID的行的数据。

如果表2中没有针对特定学生的条目,但您仍希望其在结果中显示,只需将JOIN替换为LEFT JOIN

详细了解 JOINs in mysql docs 和功能GROUP_CONCAT