DML

增、删、查、改

①插入

          a.直接插入

             insert into 表名 values (数值1,数值2),(数值3,数值4)    每个括号中的数值表示一条记录

          b.其它表中查询结果插入

             insert into 表名(列名1,列名2) select 列名1,列名2 from 被查询表名

             insert into 表名 select * from 被查询表

             当需要从多张表中查询并插入时需要将多张表中的相应的字段合成一张新表

            insert into 表名 (列名1,列名2) select * from (select a.列名1,b.列名2 from table1 a join table2 b where...) as tb

            当不加上where 语句时会将a表中的列名1和b表中的列名2两两组合成为一张新表tb,加上where语句后按条件查询并将查询结果组成一张新表

           select * from (select a.dept_name,b.dept_no from dept a,stu b where a.dept_no=b.dept_no) as tb 和jion语句等效

          c.向表中的unique或primary key行插入重复列时,会出错,可以使用以下命令

             insert into 表名 values (......) on duplicate key update 列名=‘’

             向表中插入数据,当插入的数据在表中的unique或primary key行没有重复数据时,正常插入,否则,将执行后面的update操作,将与插入数据相同的一行中对应的列名中的              数据更新为update 后面的数据。

②更新

          a.直接更新

             updata 表名 set 字段名=“” where...当需要将整张表的某个字段更新为相同的数值的时候,使用where语句满足一个均服从的条件,如id<>-1

         b.用一张表中的数据更新另一张表

             updata 更新表名 set 字段名=(select 字段名 from 被更新表名 where 更新表名.字段=被更新表名.字段)

         c.使用游标批量更新

            use db;
            drop procedure if exists my_proc;
            delimiter %
            create procedure my_proc()
            begin
            declare num int default 0;
            declare cur_test cursor for select book_no from lib;
            declare exit handler for not found close cur_test;
            set @i=1;
            open cur_test;
            repeat
            fetch cur_test into num;
            update lib set book_num=@i where book_no=num;
            set @i=@i+1;
            until 0 end repeat;
            close cur_test;
            end;

③删除

            delete from 表名 where ....   条件删除并且删除数据存储在系统回滚段中,可以回滚

            truncate table 表名              删除全部数据,且不能回滚

            多表删除

            delete a,b from table1 a,table2 b where a.no=b.no and a.no=3

④查询

           a.查询不重复的记录

           select distinct 字段名 from 表名 where ...order by 字段名[asc | desc] [limit 起始偏移量,显示数据总数]

           b.选择数据插入一张新表

           select 字段名... into 表名 where ...   这时要求这张表之前是不存在的,与insert into    select 有区别,insert into select 要求表必须存在

           c.聚合

           select 字段名 from 表名 where ... group by 字段名 having 条件

           d.表连接(内连接([inner] join / where a.列名=b.列名)和外连接(left join / right join))

           e.子查询

              use db;
              select dept.dept_name,stu.stu_name from dept,stu where dept.dept_no=stu.stu_no;

⑤联合

          union      :将union all 的结果去重

          union all :把所有查询出来的结果直接合并到一起    

          use db;
          select dept_no from stu
          union all
          select dept_no from dept;

⑥复杂查询

select s.stu_no,s.stu_name,t.maxage from 
stu s inner join
(select s.stu_no,max(s.age) as maxage from stu s group by s.dept_no)t
on s.stu_no=t.stu_no
where t.maxage=s.age;

            

             

        

原文地址:https://www.cnblogs.com/-cqq/p/8028366.html