如何根据 MySQL 中的科目将学生分数显示在单列中?


为此,请使用 UNION ALL。

我们首先创建一个表

mysql> create table DemoTable729 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   MySQLMarks int,
   CMarks int,
   JavaMarks int
);
Query OK, 0 rows affected (0.40 sec)

使用 insert 命令在表中插入一些记录

mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('Chris',94,67,75);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('Robert',45,99,54);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('David',57,89,43);
Query OK, 1 row affected (0.12 sec)

使用 select 语句从表中显示所有记录

mysql> select *from DemoTable729;

这将产生以下输出 -

+-----------+-------------+------------+--------+-----------+
| StudentId | StudentName | MySQLMarks | CMarks | JavaMarks |
+-----------+-------------+------------+--------+-----------+
| 1         | Chris       | 94         | 67     | 75        |
| 2         | Robert      | 45         | 99     | 54        |
| 3         | David       | 57         | 89     | 43        |
+-----------+-------------+------------+--------+-----------+
3 rows in set (0.00 sec)

以下是对单列中显示学生分数的查询

mysql> select StudentId,StudentName,'MySQL' as SubjectName, MySQLMarks as Score
from DemoTable729
UNION ALL
select StudentId,StudentName, 'C' as SubjectName, CMarks as Score
from DemoTable729
UNION ALL
select StudentId,StudentName, 'Java' as SubjectName, JavaMarks as Score
from DemoTable729;

这将产生以下输出 -

+-----------+-------------+-------------+-------+
| StudentId | StudentName | SubjectName | Score |
+-----------+-------------+-------------+-------+
| 1         | Chris       | MySQL       | 94    |
| 2         | Robert      | MySQL       | 45    |
| 3         | David       | MySQL       | 57    |
| 1         | Chris       | C           | 67    |
| 2         | Robert      | C           | 99    |
| 3         | David       | C           | 89    |
| 1         | Chris       | Java        | 75    |
| 2         | Robert      | Java        | 54    |
| 3         | David       | Java        | 43    |
+-----------+-------------+-------------+-------+
9 rows in set (0.00 sec)

更新于: 22-Aug-2019

2K+ 次浏览

开启你的 职业

完成课程,获取认证

开始
广告