在MySQL中实现列转行可以使用UNION ALL操作符来实现。以下是一个示例:
假设有一个表格students
,包含以下5列:id, name, subject1, subject2, subject3
,内容如下:
id | name | subject1 | subject2 | subject3 |
---|---|---|---|---|
1 | Alice | Math | English | Science |
2 | Bob | History | Math | English |
要将这个表格的subject1, subject2, subject3
列转换为行数据,可以使用以下SQL查询:
SELECT id, name, 'subject1' as subject_name, subject1 as subject_value FROM students
UNION ALL
SELECT id, name, 'subject2' as subject_name, subject2 as subject_value FROM students
UNION ALL
SELECT id, name, 'subject3' as subject_name, subject3 as subject_value FROM students
这个查询将原表格的每一行转换为三行,每一行包含id, name, subject_name, subject_value
列,其中subject_name
列表示原来的subject1, subject2, subject3
列的名称,subject_value
列表示对应的值。
执行以上SQL查询后,得到的结果如下:
id | name | subject_name | subject_value |
---|---|---|---|
1 | Alice | subject1 | Math |
1 | Alice | subject2 | English |
1 | Alice | subject3 | Science |
2 | Bob | subject1 | History |
2 | Bob | subject2 | Math |
2 | Bob | subject3 | English |