DQL语言(data query language,数据查询语言)
- 查询数据库数据,如select语句
- 简单的单标查询或多表的复杂查询和嵌套查询
- 数据库中最核心最重要的语句
- 使用评率最高的语句
select语句语法
[]代表可选的,{}代表必须的
as子句
- as子句可以给数据列和表取别名
- 可以吧经计算或总结的结果用另一个新名称来代替
- as可以省略不写
指定查询的字段
查询表中所有的数据列结果
select * from 表名 (不推荐使用,效率不高)
查询表中指定的结果数据列(可以取别名)
select name from 表名 (只查询name)
select t.name n t.age a from teacher as t; (取别名查询)
查询多个表有同名的字段,用(表名.字段)指定该字段属于那个表
select t.name,s.age from teacher as t ,student as s;
distinct关键字
all 关键字是默认的,即显示所有的记录,distinct与之相反,是去掉select查询返回的记录中重复的记录
select distinct 字段1,字段2... from 表名
查询不重复的studentno
select distinct studentno from result; (部分去重)
select distinct * from result; (整行去重)
添加组外界依赖
表中某列依赖于另一张表的某列,需要在常见表时增加这一行
constraint 外键名 foreign key (依赖外表的列) references 被依赖的表(被依赖的列)
- 方式一
直接在创建表时再表后加
constraint FK_GradeId foreign key (GradeID) references grade(GradeID)
- 方式二
先创建表再增加外键
alter table subject add constraint FK_gradeid2 foreign key(gradeid) references grade(gradeid);
- 删除外键
alter table subject drop foreign key FK_gradeid2;
select使用表达式
表达式一般有文本值,列值,null,函数和操作符等组成
应用场景:
select语句返回结果列中使用
select语句的order by,having等子句中使用
dml语句中的where条件语句中使用表达式
#运算
select studentresult*0.7 from result;
select 1+3;
#给返回结果中的课时都加10个小时
select subjectname "课程名称", classhour+10 as "新学时" from subject;
where 条件语句
- 用于检索数据表中符合条件的记录
- 搜索条件可有一个或多个逻辑表达式组成,结果一般为真或假
- 搜索条件的组成(逻辑操作符,比较操作符)
select * from result where studentresult=100 and subjectno=1;
select studentresult from result where studentresult between 80
and 90;
- 逻辑操作符
操作符名称 | 语法 | 描述 |
---|---|---|
and或&& | a and b 或 a && b | 逻辑与,同时为真,结果才为真 |
or或\\ | a or b 或 a\\b | 逻辑或,只要一个为真,则结果为真 |
not 或 ! | not a 或 !a | 逻辑非,若操作数为假,结果则为真 |
- 比较操作符
操作符名称 | 语法 | 描述 |
---|---|---|
is null | a is null | 若操作符为null,则结果为真 |
is not null | a is not null | 若操作符不为null,则结果为真 |
between | a between b and c | 若a范围在b与c之间则为真 |
like | a like b | sql模式匹配,若a匹配b,则结果为真 |
in | a in(a1,a2,a3…) | 若啊等于a1,a2,a3…中的某一个,则结果为真 |
update修改表内数据
update 表名 set 要修改的列=要修改的内容 where 判断条件
update teacher set name="冰冰" where id=1;