SQL常用关键字与函数

220 阅读3分钟

SQL基础

Structured Query Language 结构化查询语言

关键词

create

create table employees(
	no int primary key, // 主键
	name varchar(9) not null, // varchar 长度可变的字符,MAX为9,不能为空;char为不可变
	salary numeric(7,2), //总位数为7,小数点后精度为2
	onboarding date(2022--06-06);
)

insert

image.png

insert into table1 value();
insert into table1 values();
insert into table1(prop1,prop2,prop3) values(value1,value2,value3);

主键

主键约束 唯一标识,不能为空

select

select props from table1;
select * from table1;

distinct

distinct - 独特的 adj.

同一字段中可能会出现重复值,使用关键词distinct可以去掉重复值

//查询table1中的prop1属性,去掉重复值,查询唯一值
select distinct prop1 from table1;

where

选取特定的数据 : select 字段名 from 表名 where 字段 运算符 值;

查询table1prop2等于value2的数据,并打印其prop1的值

select porp1 from table1 where porp2=value2;

运算符

image.png

and/or

查询table1prop2等于value2且prop3大于value3的数据,并打印其prop1prop4的值

select porp1,prop4 from table1 where porp2=value2 and prop3>value3;
select * from table1 where (prop1=value1 or prop2=value2) and prop3>value3

like

模糊查询 用法像是Linux的*通配符

select * from table1 where prop1 like 'value1%'
select * from table1 where prop1 like '%value2'

in

指定多个搜索条件可以匹配的值,实际上是多个or条件的合并

也有not in,表示in的取反数据集

select * from table1 where prop1 in (value1, value2, value3)
//等同于👇
select * from table1 where prop1=value1 or prop1=value2 or prop1=value3

//in里嵌入sql语句,把后面的select语句的输出作为前面的select语句的输入
select * from table1 where porp1 in (select prop1 form table2 where prop like '%value1');

SubQuery

子查询,嵌套查询

嵌套在where子句中的查询,为主查询返回所需数据,或对检索数据进行进一步限制

通常跟in一起使用

select * from table1 where porp1 in (select prop1 form table2 where prop like '%value1');

between

select * from table1 where prop1 between value1 and value2;

order by

对结果集进行排序,默认升序asc,使用desc降序

asc/desc放在字段后面

select * from table order by prop1 desc;

update & delete

update 表名 set 字段1=值1,字段2=值2 where …

不加入where表示表中所有记录都会更新或者删除

update table1 set prop1=value1 where prop1=value2;
update table1 set prop1=prop1+value1 where prop1=value2;
delete from table1 where prop1=value2;

index

索引可以提高访问数据的速度

create index index1 on table1(prop1,prop2,…);

view

  • 从源table中选取一部分数据创建一个view,像是一个子表,可以使用select查询内容
  • 创建view后,源table数据更新后,再次select view可以看到更新后的数据
//select返回的数据集作为输入创建一个视图
create view view_001 as select ...
//查看创建的视图
select * from view_001

image.png

null

代表遗漏的未知数据,其作用是未知的或者不适用的值的占位符

判断null的运算符:is null 或者 is not null

Alias

给字段、表创建别名

select prop1 as alias1 from table1 as alias2
//as 可以省略
select prop1 alias1 from table1 alias2

join

image.png

select * as from table1 (inner/left/right) join table2 where...;

常用函数

count(*)统计表中所有记录数量

count(prop1)统计表中prop1不为null的记录数量

count(prop1) from table1;

max(prop1)、min(prop1)、avg(prop1)、sum(prop1)

group by:结合统计函数,根据一个或多个列结果集进行分组

select prop1,avg(prop2) from table1 group by prop1;

having:对group by产生的组进行过滤

select prop1,avg(prop2) from table1 group by prop1 having avg(prop2)<value2;