跳至主要內容

DML语句小结

张威大约 4 分钟mysqlmysql核心SQL

DML语句小结

DML数据操作语言:操纵数据,针对数据的增删改查;

(1)增insert:

insert into 表名 values(数据的集合);//添加一条数据;
insert into 表名(字段名1,字段名2,字段名3) values(“数据1”,“数据2”,“数据3”); //添加指定字段数据,其他系统默认;
insert into 表名 values(数据集合1),(数据集合2),(数据集合3);//insert进行小批量数据插入

(2)删delete:

delete from 表名;//删除表中所有数据
delete from 表名 where 字段名 = “数据”; //过滤数据,符合该条件的删除;

(3)改update:

update 表名 set 字段名 = “新的数据” where 字段名 = “旧的数据”;//修改数据,有过滤条件。
update 表名 set 字段名 = “新的数据”; //修改表中所有数据

(4)查select:

1.普通查询

select * from 表名;// * 表示通匹表中所有字段,不建议使用,易泄露信息;
select 字段名1,字段名2,字段名3… from 表名;//等值于上面的查询
select * from 表名 where 字段名 = “数据”; //有过滤条件

2.去重查询

select distinct 字段名 from 表名;//重复的只出现一次

3.排序查询

select distinct 字段名 from 表名 order by 字段名;//不加asc,系统默认加升序查询
select distinct 字段名 from 表名 order by 字段名 asc;//升序排序查询
select distinct 字段名 from 表名 order by 字段名 desc;//降序排序查询

4.分组查询:Sum()相加,count统计数据个数,year获取年份

select 字段名,操作名(字段名2) from 表名 group by 字段名; //进行分组查询:先分组,再在组内查询。

5.等值查询:按照笛卡尔乘积方式处理,效率太低

6.连接查询:先将范围缩小,再按照笛卡尔乘积方式处理,效率提高。

6.1外连接查询

左外连接查询:左表过滤的结果必须全部存在;右表匹配左表过滤后的结果若匹配成功,补成功的数据,否则补NULL; 左外连接使用的十分多。

select 左表.字段名1,字段名2
from
select 字段名1,字段名2 from 左表 where 字段名2 判断条件 //过滤左表数据
left join
select 字段名1, 字段名3 from 右表 where 字段名 判断条件 //过滤右表数据
on 左表.字段名1 = 右表.字段名1

右外连接查询:右表过滤的结果必须全部存在;左表匹配右表过滤后的结果若匹配成功,补成功的数据,否则补NULL; 右外连接使用的不是非常多。

select 左表.字段名1,字段名2
from
select 字段名1,字段名2 from 左表 where 字段名2 判断条件 //过滤左表数据
right join
select 字段名1, 字段名3 from 右表 where 字段名 判断条件 //过滤右表数据
on 左表.字段名1 = 右表.字段名1

全外连接查询: 左表和右表数据全部都存在,与左外连接、右对应一边不存在则补空。**

select 左表.字段名1,字段名2
from
select 字段名1,字段名2 from 左表 where 字段名2 判断条件 //过滤左表数据
full join
select 字段名1, 字段名3 from 右表 where 字段名 判断条件 //过滤右表数据
on 左表.字段名1 = 右表.字段名1

6.2内连接查询:只筛选匹配项,不匹配不显示。

select 左表.字段名1,字段名2
from
select 字段名1,字段名2 from 左表 where 字段名2 判断条件 //过滤左表数据
inner join
select 字段名1, 字段名3 from 右表 where 字段名 判断条件 //过滤右表数据
on 左表.字段名1 = 右表.字段名1

7.聚合查询:

​ ①聚合查询1:带去重效果;

select * from 表1
union
select * from 表2;

​ ①聚合查询2:不带去重效果;

select * from 表1
union all
select * from 表2;