SQL数据库各种查询建表插入集合

时间:2021-10-16 08:19:21

创建表

drop table student;
DROP table Course;
DROP table sc;

CREATE TABLE student
(
sid
integer PRIMARY KEY autoincrement,--id
sname nvarchar(32),--学生名
age integer,--年龄
sex nvarchar(8)--性别
);
create table Course--课程表
(
cid
integer PRIMARY KEY autoincrement,--id
cname nvarchar(32)--课程名
);
create table sc --成绩表
(
scid
integer PRIMARY KEY autoincrement,--id
sid integer,--学生表id
cid integer,--课程表id
core integer--成绩
);

INSERT into student(sname,age,sex)
VALUES
(
'芳芳',21,''),
(
'婷婷',21,''),
(
'瑞宝',21,''),
(
'不知名',21,'');

insert into Course(cname)
VALUES
(
'语文'),
(
'数学');

INSERT into sc(sid,cid,core)
VALUES
(
1,1,80),
(
1,2,50),
(
2,1,99),
(
2,2,99);

各种插入

INSERT into student(sid,sname,age,sex)
VALUES
(
6,'错乱',21,'')

 

各种查询

--查询自增id不连续的id
select sid from (select sid from student order by sid asc) s where not exists (select 1 from student where sid=s.sid-1);
--连接查询,芳芳的数学成绩
select s.sname,sc.core from student s LEFT JOIN sc ON s.sid = sc.sid left JOIN Course c on c.cid =sc.cid WHERE s.sname = '芳芳';
--模糊查询名字有婷的学生
select * from student WHERE sname like '%婷%';
--不用连接查询查询婷婷 的数学成绩
select s.sid,s.sname,scc.core from (SELECT sid,sname FROM student ) s,(SELECT sid,core,cid FROM sc) scc WHERE sname = '婷婷' AND scc.sid = s.sid AND scc.cid = 2 ;
--简便多表查询芳芳以外学生的语文成绩
select s.sname,c.cname,sc.core from student s,sc,Course c WHERE s.sname IS NOT '芳芳' and s.sid = sc.sid and sc.cid = c.cid and c.cname = '语文' GROUP BY sc.scid ;
--查询出数学比语文高的学生
SELECT s.sid,s.sname,sc1.core FROM (SELECT sid,core FROM sc WHERE cid = '2' ) sc2,(SELECT sid,core FROM sc WHERE cid = '1' ) sc1, (SELECT sid,sname FROM student ) s WHERE s.sid = sc1.sid and sc1.sid = sc2.sid AND sc1.core<sc2.core;
--查询成绩100的其他学生
select * FROM student WHERE sname NOT IN (SELECT sname FROM student s,sc WHERE s.sid = sc.sid AND sc.core = 100);
--查询成绩大于60的学生个数
select count(distinct(sname)) FROM student s,sc WHERE s.sid = sc.sid AND sc.core>60;
--查询平均值大于70的学生
select s.sname,avg(sc.core) from student s,sc WHERE s.sid = sc.sid GROUP BY sc.sid HAVING avg(sc.core)>70;