-- 9、检索"01"课程分数小于60,按分数降序排列的学生信息
时间: 2024-02-05 12:10:54 浏览: 30
假设有以下三个表:
```
-- 学生表
CREATE TABLE `students` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
`gender` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- 课程表
CREATE TABLE `courses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- 分数表
CREATE TABLE `scores` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`course_id` int(11) NOT NULL,
`score` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
-- 插入数据
INSERT INTO `students` VALUES (1,'张三',18,'男'),(2,'李四',19,'女'),(3,'王五',20,'男');
INSERT INTO `courses` VALUES (1,'01'),(2,'02');
INSERT INTO `scores` VALUES (1,1,1,80),(2,2,1,70),(3,3,1,59),(4,1,2,90),(5,2,2,75),(6,3,2,85);
```
则可以使用以下SQL语句查询"01"课程分数小于60,按分数降序排列的学生信息:
```
SELECT s.id, s.name, c.name AS course, sc.score
FROM students AS s
INNER JOIN scores AS sc ON s.id = sc.student_id
INNER JOIN courses AS c ON sc.course_id = c.id
WHERE c.name = '01' AND sc.score < 60
ORDER BY sc.score DESC;
```
查询结果为:
```
+----+------+-------+-------+
| id | name | course| score |
+----+------+-------+-------+
| 3 | 王五 | 01 | 59 |
+----+------+-------+-------+
```