SQL基础教程

256 阅读4分钟

操作关系型数据库的语言,数据库Database ,DB,管理数据库的系统称为DBMS

关系型数据库使用二维表存储数据,列称为字段,行称为记录,以行为单位进行读写

数据类型

  • integer 数值型
  • char    字符型 全称character 指定长度字符串
  • varchar 字符型 不定长字符串
  • date    日期型

约束

  • not null  不为空
  • primary key 主键

DDL 数据定义语言

create 创建

create database 数据库名 ; -- 创建一个数据库
create table 表名 ; -- 创建一张表
create table 表名(
列1  数据类型   not null,
列2  数据类型   default 0,-- 默认值为03  数据类型   not null,
列4  数据类型   not null,
primary key(列1));

drop 删除

drop table 表名 ; -- 删除一张表,无法恢复

alter  修改

alter table 表名 add column 列名 ;-- 在指定表中增加一列
alter table 表名 drop column 列名;-- 在指定表中删除一列

DML 数据操作语言

select 查询

  • 注意select语句的执行顺序  from  > where  > group by > having > select > order by
-- 基础语句
select 列名 from 表名 ;-- 从指定表中查找指定列
select * from 表名 ; -- 查找整个表
select 列名 as 别名 from 表名 ;-- 使用as设置别名,中文使用双引号括起来
select distinct 列名 from 表名 ; -- 删除指定表,指定列的重复数据,null也被视为数据
-- where 条件 对select进行筛选
select 列名 from 表名 where 条件表达式; -- 从指定表中按条件查找指定列,可以使用not关键字取反
select 列名 from 表名 where 条件表达式;-- 除了基本的运算符还可以使用 and or 。and优先级高于or
-- 聚合函数
select max(列名) from 表名; -- 查找指定表,指定列的最大值
count() -- 会自动排除null ,可能会影响计算结果
sum() -- 会自动排除null ,可能会影响计算结果
avg()
max()
min()
-- group by 分组
select 列名 from 表名 group by 列名; -- 从指定表中查找指定列,之后根据指定列分组
-- having 条件 对 group by 进行条件筛选
select 列名 from 表名 group by 列名 having 条件;
-- order by 排序 desc降序 asc 升序 数据中有null会在开头或末尾汇总显示
select 列名 from 表名 order by 列名 desc; -- 查询后按指定列降序排序,排序列可以有多个,左边优先

insert 增加

insert into 表名 (列1,列2values(值1,值2) -- 插入数据
insert into 表名 (列1,列2select1,列2 form 表名 -- 从指定表中复制数据

update 更改

-- 更新数据
update 表名 set 列名 = 表达式; -- 将表中指定列 按照表达式更改,可以使用where语句

delete 删除

-- 只删除数据,不影响表结构
delete from 表名;
delete fromwhere 条件; -- 可以指定条件

DCL 数据控制语语言

  • commit  提交
  • rollback 取消
  • grant 赋予操作权限
  • revoke 取消操作权限

事务是需要在同一个处理单元中执行的一系列更新处理的集合,事务中的DML语句必须全部执行

-- 开始事务 mySQL: start transaction  SQL server\ PostgrSQL : begin transaction
start transaction;
	DML语句省略
commit --提交事务,执行以上内容
rollback --取消事务,不执行以上内容

SQL进阶——复杂查询

子查询

-- 子查询可以在select的任意子句中使用 比如where等,但是where中返回的结果只能有一个
select 列名  from (select 列名 from 表名) -- 根据内层结果 查询外层结果

union 并集查询

select a from a 
union all -- all可选,表示是否保留重复行
select b from b ; -- 结果返回两个表指定列的并集 (加法)

intersect 交集查询

select a from a 
intersect
select b from b ; -- 结果返回两个表指定列的交集 (共有部分)

except

select a from a 
intersect
select b from b ; -- 结果返回两个表指定列的减法 去掉aa列中bb列的剩余部分

inner join 内联结

select b.a,c.a 
	from  b inner join c
	on 表b.列1 = 表c.列1;-- 纵向拼接两张表,根据on中的条件,选出同时存在两张表的数据

outer join 外联结

select b.a,c.a
	from  b left outer join c -- 使用leftright指定主表
	on 表b.列1 = 表c.列1;-- 横向拼接两张表,根据on中的条件,选出主表的所有数据,副表会选出同时存在的数据