MySQL DML

  1. 插入记录
    -- 插入一条记录
    insert into 表名(字段1,字段2……) values(值1,值2……)
    -- 插入多条数据
    insert into 表名(字段1,字段2……) values(值1,值2……),(值1,值2……),……
  2.  修改记录
    -- 修改满足条件所有记录
    update 表名 set 字段=值,字段2=值,…… where 条件
  3. 删除记录
    -- 删除满足条件的所有记录
    delete from 表名 where 条件
  4. 查询
    -- 显示满足条件的字段
    select 字段1,字段2 from 表 where 条件
  5. 别名
    select 字段名 as 字段别名 from 表名 as 表别名;
    -- as可以简写为空格
  6. 在……之间
    -- 获取字段值在两个值之间的记录
    select * from 表 where 字段 between 值 and 值;
  7. 交集
    -- 只返回同时满足所有条件的记录
    select * from 表名 where 条件1 and 条件2;
  8. 模糊查询
    -- 查询book表中姓曹的作者写的书
    select * from book where author like '曹%'
  9. 取反
    -- 返回不满足条件的记录
    select * from 表名 where not 条件
  10. 子查询
    -- 先查询从出一个数据集,把这个数据集变成一张表。
    -- 从goods表中查出price大于100的记录,再从这些记录中查出name带水的记录
    select * from (select * from goods where price > 100) A where A.name like '%水%'
  11. 排序
    -- desc根据字段降序,asc根据字段升序
    order by 字段 desc
  12. 分支
    case when 条件 then 结果
    	when 条件2 then 结果2
    	else 结果3
    end
  13. 限制条数
    limit 起始位置,总条数
  14. 分组和聚合
    聚合函数
    	如果单独用聚合函数,是对查询的数据进行聚合
    	sum 
    	avg
    	max
    	min
    	count
    	
    group by
    	分组
    	通常跟聚合函数一起使用,这时候是对分组之后的数据进行聚合。
    having
    	条件
    	跟where的区别:
    		where是分组前加条件,having是分组后加条件
  15. 编写顺序
    编写顺序  select ....from ... where ....group by .... having.....order by....limit
    		(1)from---确认数据源
    		(2)where--- 将满足where条件的数据放在查询结果中
    		(3)group by --- 对where条件查询出来的结果进行分组
    		(4)having --- 对组进行筛选,留下有用的组
    		(5)select -- 根据select里的显示要求,对有用的数据进行统计计算和筛选
    		(6)order by -- 对统计好的数据进行排序 
    		(7)limit 
  16. 合并
    -- 合并两个数据集
    select * from goods where price>100
    union 
    select * from goods where price <50
    
    -- 合并两个数据,但是表可以不是同一张表,只要求字段数量一定要相同
    select id,name,price from goods
    union 
    select id,income,employee_id from orders;
    -- union 会把重复的数据合并
    -- union all 会显示重复的数据
  17. exists
    -- exists可以快速查出满足条件的数据
    -- exists的使用条件为
    -- 1.查询字段只在exists外的表里
    -- 2.查询速度要快
    
    select * from score b where sno in (
    	select 1 from student a where a.sno = b.sno
    );
    -- 不会获取student表中的数据
posted @ 2022-01-04 22:18  还是减肥吧  阅读(31)  评论(0编辑  收藏  举报