1. 程式人生 > >筆試題-sql語句

筆試題-sql語句

ima upd let 寫法 技術分享 .com 改進 建表語句 做出

今天遇到了不熟練(不會)的查詢題目

  • 回來自己又做了一下,如下

建表語句


-- Table structure for score
-- ----------------------------
DROP TABLE IF EXISTS score;
CREATE TABLE score (
id int(11) DEFAULT NULL,
sno int(11) DEFAULT NULL,
name varchar(255) DEFAULT NULL,
subject varchar(255) DEFAULT NULL,
score varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- Records of score
-- ----------------------------
INSERT INTO score VALUES (‘1‘, ‘201201‘, ‘小明‘, ‘math‘, ‘90‘);
INSERT INTO score VALUES (‘2‘, ‘201202‘, ‘小李‘, ‘math‘, ‘99‘);
INSERT INTO score VALUES (‘3‘, ‘201203‘, ‘小紅‘, ‘math‘, ‘43‘);
INSERT INTO score VALUES (‘4‘, ‘201201‘, ‘小明‘, ‘en‘, ‘66‘);
INSERT INTO score

VALUES (‘5‘, ‘201202‘, ‘小李‘, ‘en‘, ‘56‘);
INSERT INTO score VALUES (‘6‘, ‘201203‘, ‘小紅‘, ‘en‘, ‘88‘);
INSERT INTO score VALUES (‘7‘, ‘201201‘, ‘小明‘, ‘computer‘, ‘99‘);
INSERT INTO score VALUES (‘8‘, ‘201202‘, ‘小李‘, ‘computer‘, ‘65‘);
INSERT INTO score VALUES (‘9‘, ‘201203‘, ‘小紅‘, ‘computer‘, ‘67‘);
INSERT INTO score
VALUES (‘11‘, ‘201204‘, ‘小白‘, ‘sss‘, ‘99‘);
INSERT INTO score VALUES (‘11111‘, ‘201203‘, ‘小紅‘, ‘computer‘, ‘67‘);

  • 題目1:找到所有分數都及格(>=60)的學生。

    1. 查詢有科目分數小於 60 的, 然後 not in 即可
      select name from score where sno not in
      (select s.sno from score s where s.score < 60) GROUP BY sno

    2. not exists 寫法
      select name from score s1 where not exists
      (select 1 from score s where s.score < 60 and s1.sno = s.sno) GROUP BY s1.sno

    3. having 篩選
      select * from score s GROUP BY s.sno having min(s.score) >= 60

  • 題目2:表中有冗余記錄,如何刪除?如下圖:

技術分享圖片

分析:找到該數據對應的id,根據id刪除!

select s.id from score s group by s.sno,s.name,s.subject,s.score -- 此結果不包含需要刪除的id
本以為是:delete from score where id not in (select s.id from score s group by s.sno,s.name,s.subject,s.score )

  • 結果毫不猶豫的拋出錯誤:
    技術分享圖片
  • 查明原因,mysql認為delete/update 跟 子句裏面select到的不能是一張表

  • 做出改進(表起別名,按照需要刪掉新插入的或者後插入的)

delete from score where id not in (select id from (select min(id) id from score s group by sno,name,subject,score )t)

筆試題-sql語句