数据的插入,查询,修改,删除

数据的插入,查询,修改,删除

1.数据插入

insert into <数据表名>  [(列名1,列名2,列名3....)]
[values(<列值1,列值2,列值3...>)]
[<子查询>]

注意:若某些列(属性)在into子句中未出现,则记录在未出现的对应列上取空值。若没指明任何列名,则插入新纪录必须在指定表上都有值

--创建数据库StuManage
create database StuManage

--创建数据表
create table Student(SId varchar(10),Sname varchar(10),Sage datetime,Ssex varchar(10))

--插入单组数据
insert into Student values('01' , '赵雷' , '1990-01-01' , '男')

--指定列插入
insert into Student (SId,Sname,Sage,Ssex) values('01' , '赵雷' , '1990-01-01' , '男')

--插入子查询的结果
insert into SC (cid,sid,score)
select student.sid,Course.cid,null
from Student,Course

2.数据查询

参考笔记https://note.youdao.com/ynoteshare1/index.html?id=45d4298f42397bd52ccf6fc716e27ee9&type=note#/

这里列出几种特殊的查询及其用法

  • 查询SC表中被选课程最多的课程信息

使用 with <临时表名> as (子查询)作为一个临时查询语句块使用

with t1 as
(
	select cid,count(*) as cnt 
	from sc 
	group by cid 
)
select Course.*
from Course,t1
where Course.cid=t1.cid AND t1.cnt=(select max(t1.cnt) from t1)
  • 查询被选课课程最多的课程号
select  top 1 cid
from sc
group by cid
order by count(*)

所以第一个问题还可以这么查

select course.*
from course
where course.CId=
(select  top 1 cid
from sc
group by cid
order by count(*))
  • 查询被选课程次数最多的前三门课的信息

    多行比较运算符

    in

    not in

    any (<any, >any ,<>any)

    all (<all, >all ,<>all)

    
    select course.*
    from course
    where course.CId in
    (select  top 3 cid
    from sc
    group by cid
    order by count(*))
    

3.数据修改

格式

update 表名
set  列名1=1 [,列名2=2]
[where 条件]

其中条件可以嵌入子查询

  • 把所有人的年龄+1

    update student
    set Sage=Sage+1
    
  • 将计算机科学系的全体学生成绩置为0

    update sc
    set Grade=0
    where 'cs'=
    		( select Sdept
    		 from student
    		 where student.Sno=SC.Sno
    		)
    

4.数据删除

delete 
from 表名
[where 条件]

不过与update 操作一样,一次只能操作一个表,这样可能会造成数据不一致问题

  • 删除选课表SC中成绩为null的学生

    delete from SC 
    where SC.score is null
    
全部评论

相关推荐

01-17 12:35
吉首大学 Java
秋招之BrianGriffin:自己的工作自己做!😡
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务