SQL语言汇总

1、主键和外键:

 如果一个表的某一列是另一个表的主键,则该列被称为外键。

外键是连接两个表的纽带,通过外键与主键的等值连接,可以将表中的不同信息相关联起来。

create table student(
 sno varchar(20) primary key,//学号是主键
 sname varchar(30),
 sage int,
 sdept varchar(255), //系号
foreign key(sdept) references(course(cno)) 
);

create table course(
cno varchar(20) primary key,//系号是主键
cname varchar(20),
credit int//学分
);

2、删除一张表中所有冗余的数据

delete from student
where sno not in(
 select sno from(
   select min(sno) as sno
   from student
   group by sname,sage,sdept)a
 )
);

3、查询001课程比002课程成绩高的所有学生的学号

Student(Sid,Sname,Sage,Ssex)学生表
Sid:学号
Sname:学生姓名
Sage:学生年龄
Ssex:学生性别
Course(Cid,Cname,T#)课程表
Cid:课程编号
Cname:课程名称
SC(Sid,Cid,score)成绩表
Sid:学号
Cid:课程编号
score:成绩
select a.id from
(select sid,score from sc where cid='001')as a,
(select sid,score from sc where cid='002')as b,
where a.sid=b.sid and a.score>b.score;

4、查询平均成绩大于60分的同学的学号和平均成绩

select sid,avg(score)
from sc
group by sid
having avg(score)>60;

5、查询所有姓“李”的同学的个数:

select count(sname)
from student
where sname like '李%';

5、修改王明同学的名字为张三

update student
set sname='张三'
where sname='王明';

6、用一条sql语句查询出每门课程都大于80分的学生姓名

select sname
from sc
group by sname
having min(score)>80;

7、查询每门课程的最高分的学生的姓名

select b.* 
from (select subject,max(score) m from grade GROUP BY subject) t,grade b 
where t.subject=b.subject and t.m=b.score

猜你喜欢

转载自blog.csdn.net/qq_40170007/article/details/88383349