mysql列转行举例
时间: 2023-11-16 13:02:15 浏览: 92
mysql 行转列和列转行实例详解
MySQL中的列转行操作可以使用UNION ALL操作符实现。下面是一个简单的例子:
假设有一个名为"students"的表,包含了学生的姓名和不同科目的成绩:
| name | math_score | english_score | science_score |
|--------|------------|---------------|---------------|
John | 90 | 85 | 92 |
| Alice | 80 | 95 | 88 |
| Bob | 75 | 81 | 90 |
如果我们想要将科目和成绩转换为行的形式,可以使用UNION ALL操作符来实现:
```
SELECT name, 'math' AS subject, math_score AS score FROM students
UNION ALL
SELECT name, 'english' AS subject, english_score AS score FROM students
UNION ALL
SELECT name, 'science' AS subject, science_score AS score FROM students;
```
执行以上操作后,将得到以下结果:
| name | subject | score |
|--------|----------|-------|
| John | math | 90 |
| Alice | math | 80 |
| Bob | math | 75 |
| John | english | 85 |
| Alice | english | 95 |
| Bob | english | 81 |
| John | science | 92 |
| Alice | science | 88 |
| Bob | science | 90 |
以上结果将每个学生的每个科目和对应的成绩转换为行的形式。
阅读全文