插入 2 (重要)
insert
into student(Sno, Sname, Ssex, Sdept, Sage)
values('201215128','陈冬','男','CS',18);
删除(与select语句格式相同)
DELETE
FROM sc
WHERE Cno = 1;
增加列(alter对应改变,table对应from,改变类型)
ALTER
TABLE Student
ADD Sbirthday datetime NULL;
ALTER
TABLE SC
CHANGE Grade Grade INT;
更新
update sc
SET Grade = 89
WHERE Cno = 3 AND Sno = 201215122;
---------------------------------------------------------------------
建视图 2(与select语句一一对应)
create VIEW Boy_Student AS
select * From student WHERE ssex='男';
创建表(与创建视图一样,把as_select换成()即可 )
CREATE TABLE sc(
Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT,
PRIMARY KEY(Sno,Cno),
FOREIGN KEY(Sno) REFERENCES Student(Sno),
FOREIGN KEY(Cno) REFERENCES Course(Cno)
);
创建数据库(与创建表一样)
CREATE DATABASE Student_DB;
SHOW DATABASES;
USE Student_DB;
---------------------------------------------------------------------
单表查询条件 2
SELECT * FROM Student
WHERE Class=95031 OR Ssex='女'
平均成绩avg,子查询 2
(DISTINCT 可以消除重复数据,可以select DISTINCT sno from score;)
(AVG计算的时候去掉重复数据,所以加一个distinct)
SELECT AVG(DISTINCT Degree)
FROM Score
WHERE Sno IN(
SELECT Sno
FROM Student
WHERE Class=95031
)
函数查询
SELECT COUNT(DISTINCT Sno) //不能与*一起用,*可以单独用
FROM Student
WHERE Class=95031;
分组查询 2
每组只选择一个显示, having判断是否显示该组(根据整租), where根据显示结果判断是否显示
SELECT Sno
FROM Score
GROUP BY Sno
HAVING MIN(Degree)>70 AND MAX(Degree)<90
多表查询 4
因为可能有两个name列,所以多表的时候,用表名.列名区分
SELECT Teacher.Tname, Course.Cno, Score.Degree
FROM Teacher, Course, Score
WHERE Teacher.Tno= Course.Tno AND Course.Cno= Score.Cno AND Teacher.Tname='张旭'
连接查询
是多表查询的一种,多表基于笛卡尔积,连接以一张表全部数据为根基
等值连接即内连接(INNER JOIN),等价于where写法
自然连接(范围更大)即外连接,分为LEFT OUTER JOIN 和RIGHT OUTER JOIN
SELECT s.id, s.name, s.class_id, c.name class_name, s.gender, s.score
FROM students s
LEFT OUTER JOIN classes c
ON s.class_id = c.id;
字符串查询
"%":能匹配任意长度的字符,"_":只能匹配任意一个字符。
SELECT * FROM Student WHERE Sname LIKE '%王%';
查询空值
SELECT * FROM 表名 WHERE 字段名 IS NULL;
SELECT * FROM 表名 WHERE 字段名 IS NOT NULL;
---------------------------------------------------------------------
触发器
插入学生信息后,新建默认选课并给null成绩
Create trigger t2
AFTER delete ON student FOR EACH ROW
BEGIN
UPDATE course
SET Tno = NULL
WHERE Tno = old.Tno;
END
存储函数
本质一样,存储函数的限制比较多,例如不能用临时表,只能返回一个变量,而存储过程的限制较少。
drop function if exists myfunc;
create function myfunc(a int, b int) returns int
begin
declare str char(3);
declare x int default 0;
declare bir datetime default null;
set x=a+b;
return x;
end
select myfunc(2,3);
存储过程
drop procedure if exists myproce;
Create procedure myproce()
begin
declare i int default 1;
while i <> 10 do
select i;
set i = i+1;
end while;
end
call myproce;
游标(指向一个select查询结果)
declare mycursor CURSOR for
SELECT `Sno`, `Sbirthday` FROM `Student` ORDER BY `Sno`;
OPEN mycursor; //打开游标
FETCH mycursor INTO na, birth; //检索游标(拿出一行,把该行的各个列值保存到各个变量中)
CLOSE mycursor;
参考资料:
结合实验1,2,3阅读