1. 程式人生 > >SQL數據庫各種查詢建表插入集合-待續持續更新

SQL數據庫各種查詢建表插入集合-待續持續更新

自增id nbsp 數學 tinc sql lec 個數 reat 其他

創建表

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;

SQL數據庫各種查詢建表插入集合-待續持續更新