SQL-basic statement exercises

The main purpose is to make a preliminary summary of some frequently encountered SQL statements. You can check the degree of sql learning, and further consolidate and strengthen the SQL statement.

Ready to work

  • First, you need to create four tables, namely: student (student table), teacher (teacher table), score (score table), course (course table)
  • Table creation SQL and initial data preset
  • student:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `stuNo` int(10) NOT NULL,
  `stuName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `stuSex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `stuAge` int(255) DEFAULT NULL,
  PRIMARY KEY (`stuNo`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '张一', '男', 15);
INSERT INTO `student` VALUES (2, '张二', '女', 35);
INSERT INTO `student` VALUES (3, '张三', '女', 27);
INSERT INTO `student` VALUES (4, '张四', '男', 15);

SET FOREIGN_KEY_CHECKS = 1;
  • teacher:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `teaNo` int(11) NOT NULL,
  `teaName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`teaNo`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, '孙一');
INSERT INTO `teacher` VALUES (2, '孙二');

SET FOREIGN_KEY_CHECKS = 1;
  • score:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for score
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score`  (
  `id` int(11) NOT NULL,
  `stuNo` int(11) DEFAULT NULL,
  `cNo` int(11) DEFAULT NULL,
  `score` int(255) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of score
-- ----------------------------
INSERT INTO `score` VALUES (1, 1, 1, 60);
INSERT INTO `score` VALUES (2, 1, 2, 25);
INSERT INTO `score` VALUES (3, 1, 3, 56);
INSERT INTO `score` VALUES (4, 1, 4, 100);
INSERT INTO `score` VALUES (5, 1, 5, 63);
INSERT INTO `score` VALUES (6, 2, 1, 5);
INSERT INTO `score` VALUES (7, 2, 2, 29);
INSERT INTO `score` VALUES (8, 2, 3, 59);
INSERT INTO `score` VALUES (9, 2, 4, 60);
INSERT INTO `score` VALUES (10, 2, 5, 65);
INSERT INTO `score` VALUES (11, 3, 1, 60);
INSERT INTO `score` VALUES (12, 3, 2, 100);
INSERT INTO `score` VALUES (13, 3, 3, 88);
INSERT INTO `score` VALUES (14, 3, 4, 75);
INSERT INTO `score` VALUES (15, 3, 5, 65);
INSERT INTO `score` VALUES (16, 4, 1, 60);
INSERT INTO `score` VALUES (17, 4, 2, 57);
INSERT INTO `score` VALUES (18, 4, 3, 86);
INSERT INTO `score` VALUES (19, 4, 4, 73);
INSERT INTO `score` VALUES (20, 4, 5, 62);

SET FOREIGN_KEY_CHECKS = 1;
  • course:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course`  (
  `cNo` int(11) NOT NULL,
  `cName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `cTeacher` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`cNo`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES (1, '数学', '1');
INSERT INTO `course` VALUES (2, '语文', '1');
INSERT INTO `course` VALUES (3, '英语', '2');
INSERT INTO `course` VALUES (4, '美术', '2');
INSERT INTO `course` VALUES (5, '音乐', '2');

SET FOREIGN_KEY_CHECKS = 1;

Table description

The attributes of the four tables created above are explained.

  • Student table: the main four attributes StuNo (primary key) student's student number, stuName student's name, stuSex student's gender, stuAge student's age
    image
  • teacher teacher table: mainly two attributes: teaNo (primary key) the teacher's job number, teaName the teacher's name
    image
  • Score table: There are mainly four attributes: id (primary key), stuNo (associated with the student table) student number, cNo (associated with the curriculum) course number, score score
    image
  • course course table: cNo (primary key) course number, cName course name, cTeacher (associated with teacher table) teacher job number
    image

Classic SQL statement exercises

It is recommended that you try to solve it yourself first, and then look at the analysis and specific code when you encounter difficulties. If you have better ideas or different opinions, you are welcome to discuss in the comment area.

  • Query the student ID of all students whose grades in "1" course are higher than those in "2" course
select a.stuNo from score a,score b where a.cNo='1'and b.cNo='2' and  a.stuNo=b.stuNo and a.score>b.score;

This is relatively simple. It mainly reads data from two tables and searches through the same student number.

  • Query the student ID and average score of students with an average score greater than 60 points
select stuNo,AVG(score) from score group by stuNo  having avg(score)>60  ;

First use the AVG function to take the average, and then use group by to group

  • Query the student ID, name, number of courses, and total score of all students
select a.stuNo,a.stuName,count(cNo),sum(score) from student a,score b  where a.stuNo=b.stuNo  group by a.stuNo,a.stuName  ;

Similar to the above one, mainly use count to count and sum for sum

  • Query the number of teachers with the surname "Sun"
SELECT count(teaName) ,'孙'as 'Name'from teacher WHERE teaName like '孙%'

Mainly use like similar query, and use% for adaptation, and use as to display

  • Query the student ID and name of the students who have not studied the class of "Sun Yi"
select stuName from student where stuNo not in (select stuNo from score where cNo in(select a.cNo from course a,teacher b where b.teaNo=a.cTeacher and b.teaName ='孙一'))

It is mainly divided into three steps: first query what lessons Sun Yi teaches, then use in to query which students have taken these courses, and then use not in to query the students who are not included in them.

  • Query the student ID and name of all students whose grades of course number "2" are lower than those of course number "1"
方法一:
SELECT a.stuNo,a.stuName from student a,score b ,score c WHERE a.stuNo=b.stuNo and a.stuNo=c.stuNo and b.cNo='2'and c.cNo='1'and b.score <  c.score;
方法二:
select stuNo,stuName from student  where stuNo in   (select a.stuNo from score a,score b  where a.cNo='1' and b.cNo='2' and a.stuNo=b.stuNo and a.score>b.score)

The first method is similar to the first. It’s just to compare the results

The second method is to change the wording to operate

  • Query the student ID and name of students who have not studied all courses
SELECT  a.stuNO,a.stuName FROM student a, score b WHERE a.stuNo=b.stuNo  group by b.stuNo having count(b.cNo)<(select count(cNo) from course)

It is to compare the total number of courses selected by the students with the total number of courses,

  • Query the student ID and name of at least one course that is the same as the student whose student ID is "1"
select distinct a.stuNo,stuName from student a,score b  where a.stuNo=b.stuNo and cNo in (select cNo from score where stuNo='1')

First find out the courses chosen by the student with student number one, and then search

  • Query the highest and lowest scores of each subject: display in the following format: course ID, highest score, lowest score
select  cNo,max(score) as 最高分,min(score) as 最低分 from score  group by cNo
  • Delete "2" classmate's "1" course grades
delete from score where stuNo='2' and cNo='1'
  • Query the information of other students who are learning the same courses as the students with "01"
SELECT * from student WHERE stuNo in (SELECT  stuNo FROM score WHERE cNo in(SELECT distinct cNo FROM score WHERE stuNo='01')and stuNo<>'01'GROUP BY stuNo having count(cNo)>=4);
  • Query the student ID, name and average grade of students who failed two or more courses
select a.stuNo,a.stuName,b.平均成绩 FROM student a right join (select stuNo,AVG(score)平均成绩 from score where score<60 group by stuNo having COUNT(score)>=2)b on a.stuNo=b.stuNo;
  • Query the highest score, lowest score and average score of each subject: display in the following format: course ID, course name, highest score, lowest score, average score, pass rate, medium rate, excellent rate, excellent rate pass >=60, Moderate: 70-80, Excellent: 80-90, Excellent: >=90
select distinct A.cNo,cName,最高分,最低分,平均分,及格率,中等率,优良率,优秀率 from score A
left join Course on A.cNo=course.cNo
left join (select cNo,MAX(score)最高分,MIN(score)最低分,AVG(score)平均分 from score group by cNo)B on A.cNo=B.cNo
left join (select cNo,(((sum(case when score>=60 then 1 else 0 end)*1.00)/COUNT(*))*100)及格率 from score group by cNo)C on A.cNo=C.cNo
left join (select cNo,(((sum(case when score >=70 and score<80 then 1 else 0 end)*1.00)/COUNT(*))*100)中等率 from score group by cNo)D on A.cNo=D.cNo
left join (select cNo,(((sum(case when score >=80 and score<90 then 1 else 0 end)*1.00)/COUNT(*))*100)优良率 from score group by cNo)E on A.cNo=E.cNo
left join (select cNo,(((sum(case when score >=90 then 1 else 0 end)*1.00)/COUNT(*))*100)优秀率 
from score group by cNo)F on A.cNo=F.cNo
  • Sort by the scores of each subject, and display the ranking. If the score is repeated, the vacancy will be reserved (not reserved)
保留
select *,RANK()over(order by score desc)排名 from score;
不保留
select *,DENSE_RANK()over(order by score desc)排名 from score
  • Query the student's total score and rank it. If the total score is repeated, the ranking will remain vacant
select *,RANK()over(order by 总成绩 desc)排名 from(
select stuNo,SUM(score)总成绩 from score group by stuNo)A
  • Query the top three records of each subject
select * from(select *,rank()over (partition by stuNo order by score desc)A from score)B where B.A<=3
select * from score a where (select COUNT(*) from score where cNo=a.cNo and score>a.score)<3 order by a.cNo,a.score desc

How to improve SQL search efficiency

  • Try to avoid using * in the select clause

    • In addition, select * is used for multi-table connection, which will cause greater cost overhead
  • The where clause compares the left side of the symbol to avoid the function and moves it to the right

  • Try to avoid using in and not in

  • Try to avoid using or and use union instead

  • Make good use of the limit clause to limit the number of rows of data returned

If you are interested, there will be several articles optimized for sql in the follow-up.

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

image

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/110918192
Recommended