DML语句

DML 操作是指对数据库中表记录的操作,主要包括表记录的插入(insert)、更新(update)、删除(delete)和查询(select)。

1.插入记录

insert into 表名(name,sex,age) values('xiao','男','18');也可以不指定字段名称,但是values后面的顺序应该和字段的顺序一致:insert into 表名values('xiao','男','18'); 有字段可以为空或null  可以省略,直接更新必要的值  insert into 表名 (name age) values('xiao','20');

一次性插多条数据  insert into 表名(name,sex,age) values('xiao','男','18'), ('xiao2','男','18'), ('xiao3','男','18')

2.更新数据

update 表名 set age='16' where xiao='xiao';将xiao的年龄改为16

同时更新表emp中的字段sal 和dept中的字段deptname:upata emp a ,dept b set  a.sal=1000,b.deptname='xiao' 

3.删除记录

delete from emp where name=''xiao;  删除表emp 中的姓名为xiao的记录

一次性删除多表的数据 

delete a, b from emp a, dept b where a.deptno=b.deptno and a.deptno=3;将表 emp 和 dept 中 deptno 为 3 的记录同时都删除

4.查询记录

(1)查询不重复的记录  select distinct 字段名 from 表名

(2)排序与限制  selct * from 表名 order by 字段名 asc| desc limit  0,100

(3)聚合操作 SELECT [field1,field2,……fieldn] fun_name  FROM tablename [WHERE where_contition] [GROUP BY field1,field2,……fieldn [WITH ROLLUP]] [HAVING where_contition]

eg:select deptno,count(1) from emp group by deptno with rollup;统计各部门人数,又要统计总人数

select deptno,count(1) from emp group by deptno having count(1)>1;统计人数大于 1 人的部门

select sum(sal),max(sal),min(sal) from emp ;最后统计公司所有员工的薪水总额、最高和最低薪水: 

5.表连接

表连接分为内连接和外连接,它们之间的最主要区别是內连接仅选出两张表中互相匹配的记录,而外连接会选出其他不匹配的记录。我们最常用的是内连接 

内连接:select ename,deptname from emp,dept where emp.deptno=dept.deptno;

外连接有分为左连接和右连接,具体定义如下。
左连接:包含所有的左边表中的记录甚至是右边表中没有和它匹配的记录;select ename,deptname from emp left join dept on emp.deptno=dept.deptno;
右连接:包含所有的右边表中的记录甚至是左边表中没有和它匹配的记录;select ename,deptname from dept right join emp on dept.deptno=emp.deptno;

6.子查询

某些情况下,当我们查询的时候,需要的条件是另外一个 select 语句的结果,这个时候,就要用到子查询。用于子查询的关键字主要包括 in、not in、=、!=、exists、not exists 等。 

emp 表中查询出所有部门在 dept 表中的所有记录 ;select * from emp where deptno in(select deptno from dept);和select emp.* from emp ,dept where emp.deptno=dept.deptno 是等价的

 如果子查询记录数唯一,还可以用=代替 in: select * from emp where deptno = (select deptno from dept limit 1); 

7.记录联合

我们经常会碰到这样的应用,将两个表的数据按照一定的查询条件查询出来后,将结果合并到一起显示出来,这个时候,就需要用 union 和 union all 关键字来实现这样的功能

SELECT * FROM t1 UNION|UNION ALL SELECT * FROM t2 …… UNION|UNION ALL  SELECT * FROM tn;

UNION 和 UNION ALL 的主要区别是 UNION ALL 是把结果集直接合并在一起,而 UNION 是将UNION ALL 后的结果进行一次 DISTINCT,去除重复记录后的结果

原文地址:https://www.cnblogs.com/xyc211/p/7976370.html