带你整理面试可能会问到的 SQL 语句

Posted 南淮北安

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带你整理面试可能会问到的 SQL 语句相关的知识,希望对你有一定的参考价值。

文章目录

一、求每个班级成绩前三的学生记录

(1)新建 stu 表

-- ----------------------------
-- Table structure for stu
-- ----------------------------
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu`  (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `sname` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `score` int(255) DEFAULT NULL,
  `classid` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of stu
-- ----------------------------
INSERT INTO `stu` VALUES (1, 'Joe', 85, 1);
INSERT INTO `stu` VALUES (2, 'Henry', 80, 2);
INSERT INTO `stu` VALUES (3, 'Sam', 60, 2);
INSERT INTO `stu` VALUES (4, 'Max', 90, 1);
INSERT INTO `stu` VALUES (5, 'Janet', 69, 1);
INSERT INTO `stu` VALUES (6, 'Randy', 85, 1);
INSERT INTO `stu` VALUES (7, 'Will', 70, 1);
INSERT INTO `stu` VALUES (8, 'Chen', 85, 2);

SET FOREIGN_KEY_CHECKS = 1;

(2)新建 class 表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for class
-- ----------------------------
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class`  (
  `cid` int(255) NOT NULL AUTO_INCREMENT,
  `cname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`cid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of class
-- ----------------------------
INSERT INTO `class` VALUES (1, '1-101');
INSERT INTO `class` VALUES (2, '1-102');

SET FOREIGN_KEY_CHECKS = 1;

(3)查找每个班级成绩前三的学生记录

select * from stu s1,class
where s1.classid = class.id
and score >=select distinct s2.score from stu s2,class where s2.classid = class.id
	order by s2.score desc limit 2,1group by class.id,s1.score desc;

distinct:去除重复,返回唯一不同的值
desc:降序,默认是升序
limit i,n:i表示查询的索引值,n 表示查询结果返回的数量

二、设计一个文件夹管理系统

create table 'folder'(
    'fid' int(255) not null auto_increment,
    'fname' varchar(20),
    'preFolder' int(255),
    'createTime' datetime
)

insert into 'folder' values(1,'1.txt',null,'2021-09-27 14:35');
delete from 'folder' where 'fname' = '1.txt';
update 'folder' set 'fname' = 'new.txt' where 'fid'=2;

select * from 'folder' order by 'createTime';

三、求每个部门薪水最高的员工和部门名

给department表和员工薪水表,求每个部门薪水最高的员工Name和DepartmentName

select e.name as Name,d.departmentName as DepartmentName from employee as e join department as d on d.id=e.departmentId
where (e.departmentid,e.salary) in 
(select departmentid,max(salary) from employee group by departmentid);

以上是关于带你整理面试可能会问到的 SQL 语句的主要内容,如果未能解决你的问题,请参考以下文章

jsp中的盲区-面试可能会问到的东西

Python中一些可能会问到的面试题

99%的面试官都会问到的Java面试题

讲讲接口测试有可能会问到的面试题汇总

面试问题100问(一)

面试会问到的基本算法