mysql将每行中的多个列合并为每行中的一列

时间:2017-01-19 17:35:12

标签: mysql join concatenation

我有一张表(图片#1),其中包含另一个表的外键。该表仅包含FK / Id到另一个表,共有5列。可能并不总是有值,所以如果没有,我插入-1,这是在datagridview vb.net中完成的。每个ID都有一个名称。那么,在带有FK(图#1)的表中,有没有办法查询每个id的名称,然后为每一行加入/连接成一列?我能够进行查询并单独返回每个名字(图片#2),但无法弄清楚如何加入所有5.我对这一切都很新,所以请告诉我,如果我关闭我的摇杆和我需要采取不同的方式。谢谢。

SELECT 
s.id,
g1.name as Grade1_name,
g2.name as Grade2_name,
g3.name as Grade3_name,
g4.name as Grade4_name,
g5.name as Grade5_name,
s.Grades_Name
FROM
sort s
    LEFT OUTER JOIN
grades g1 ON g1.id = s.grade_id_1
    LEFT OUTER JOIN
grades g2 ON g2.id = s.grade_id_2
    LEFT OUTER JOIN
grades g3 ON g3.id = s.grade_id_3
    LEFT OUTER JOIN
grades g4 ON g4.id = s.grade_id_4
    LEFT OUTER JOIN
grades g5 ON g5.id = s.grade_id_5

pic #1 pic #2

1 个答案:

答案 0 :(得分:0)

我能够使用它。不确定这是否是好的代码,但它确实是我需要的。

SELECT 
s.id,
CONCAT_WS(", ", g1.name, g2.name, g3.name, g4.name, g5.name) AS GradeNames
FROM
sort s
    LEFT OUTER JOIN
grades g1 ON g1.id = s.grade_id_1
    LEFT OUTER JOIN
grades g2 ON g2.id = s.grade_id_2
    LEFT OUTER JOIN
grades g3 ON g3.id = s.grade_id_3
    LEFT OUTER JOIN
grades g4 ON g4.id = s.grade_id_4
    LEFT OUTER JOIN
grades g5 ON g5.id = s.grade_id_5