mysql 练习题
1、用一条SQL语句 查询出每门课都大于80分的学生姓名
创建数据表:
- CREATE TABLE score(
- name VARCHAR(20) NOT NULL,
- kecheng VARCHAR(20) NOT NULL,
- fenshu int(4) NOT NULL
插入数据:
INSERT INTO score VALUES ('张三','语文',81),('张三','数学',75),('李四','语文',76),('李四','数学',90), ('王五','语文',81),('王五','数学',100),('王五','英语',90);
查询语句:
- SELECT DISTINCT name
- FROM score
- WHERE name not in (SELECT DISTINCT name FROM score WHERE fenshu <= 80)
结果如下:
2、删除除了自动编号不同,其他都相同的学生冗余信息
- CREATE TABLE student(
- id INT(4) NOT NULL auto_increment,
- num INT(7) NOT NULL,
- name VARCHAR(20) NOT NULL,
- course_num VARCHAR(4) NOT NULL,
- course_name VARCHAR(20) NOT NULL,
- score INT(4) NOT NULL,
- PRIMARY KEY (id)
- );
- INSERT INTO student(num,name,course_num,course_name,score) VALUES
- (2005001,'张三','0001','数学',69),(2005002,'李四','0001','数学',89),
- (2005001,'张三','0001','数学',69);
错误sql语句:
[Err] 1093 - You can't specify target table 'student' for update in FROM clause
mysql不允许先查出表再进行更新!!!
正确sql语句:
- CREATE TABLE tmp AS
- SELECT MIN(id) AS col
- FROM student GROUP BY num, name, course_num, course_name, score;
- DELETE FROM student WHERE id NOT IN (SELECT col FROM tmp);
- DROP TABLE tmp;