mysql 常用语句

这里把mysql的基本语句进行一个归纳。
 
一、增删改
表操作
1.增 
create table user(
     id int primarty key auto_increment,
    username varchar(20)
);
2.删
drop table user;
3.改
改名 alter table user rename to user1
增加字段 alter table user add pwd varchar(20);
删除字段 alter table user drop pwd;
修改字段 alter table user modify pwd int;
修改字段名 alter table user change pwd password varchar(20);
 
 
行操作
1.增
insert into user values("小明", 13343213222);
2.删除
delete from user where id > 5; 
3.改
update user set pwd = 123 where name = "小明"
 
 
二、查询
查询是难点,特别涉及多表查询和子查询的时候
简单查询
select * from user 
 
条件查询
select * from user where name = "小明"
select* from user where name like "%明"
select* from user where id in (38,68,98)
select* from user where id between 20 and 40
 
聚合函数和分组查询
聚合函数 sum(),max(), min(), count(), avg()
 
选出名字,有超过三个用户名字都为它
select name name  from user gouup by name having count(*)>3
 
多表查询
连接类型 具体看我另一篇文章
select product.name, cid , category.name
from product left join category on product.cid = category.id  
 
子查询
 
子查询根据返回类型的不同可以分为三种:
返回一张数据表
返回一列值
返回单个值
 
返回一张数据表
select p.id, p.name, c.id, c.name
from product as p inner join (
select id,name
from category
) as c on p.cid = c.id
 
返回一列值
select p.id, p.name, p.cid
from product as p 
where cid = any
(select id
from category
where id > 70
)
 
返回单个值
select  c.id, c.name, (select sum(promotePrice) FROM product p where p.cid = c.id) as sumPrice 
from category c
 
 
如何区别相关子查询无关子查询呢?最简单的办法就是直接看子查询本身能否执行,也就是说该子查询是否会涉及外面的表,
涉及的话就是相关子查询,不涉及的话就是无关子查询
 
 
三、索引
数据量一大,索引就很重要了,能够大大提高查询速度。索引的底层实现以后我会去写文章总结一下。
 
索引类型
 PROMARY KEY(主键索引):不允许出现相同的值
 UNIQUE(唯一索引):不可以出现相同的值,可以有NULL值
 INDEX(普通索引):允许出现相同的索引内容
 fulltext index(全文索引):可以针对值中的某个单词,但效率确实不敢恭维
 组合索引:实质上是将多个字段建到一个索引里,列值的组合必须唯一
 
增加索引
alter table product add index product_index(price);
alter table product add unique (id);
alter table product add primary key(id);
 
删除索引
alter table product drop index index_name ;
alter table product drop primary key ;
 
四、sql执行顺序
      SQL语句的书写顺序和执行顺序并不一致,具体的话如下所示:
  1. FROM:对FROM子句中的前两个表执行笛卡尔积(Cartesian product)(交叉联接),生成虚拟表VT1
  2. ON:对VT1应用ON筛选器。只有那些使<join_condition>为真的行才被插入VT2。
  3. OUTER(JOIN):如果指定了OUTER JOIN(相对于CROSS JOIN 或(INNER JOIN),保留表(preserved table:左外部联接把左表标记为保留表,右外部联接把右表标记为保留表,完全外部联接把两个表都标记为保留表)中未找到匹配的行将作为外部行添加到 VT2,生成VT3.如果FROM子句包含两个以上的表,则对上一个联接生成的结果表和下一个表重复执行步骤1到步骤3,直到处理完所有的表为止。
  4. WHERE:对VT3应用WHERE筛选器。只有使<where_condition>为true的行才被插入VT4.
  5. GROUP BY:按GROUP BY子句中的列列表对VT4中的行分组,生成VT5.
  6. CUBE|ROLLUP:把超组(Suppergroups)插入VT5,生成VT6.
  7. HAVING:对VT6应用HAVING筛选器。只有使<having_condition>为true的组才会被插入VT7.
  8. SELECT:处理SELECT列表,产生VT8.
  9. DISTINCT:将重复的行从VT8中移除,产生VT9.
  10. ORDER BY:将VT9中的行按ORDER BY 子句中的列列表排序,生成游标(VC10).
  11. TOP:从VC10的开始处选择指定数量或比例的行,生成表VT11,并返回调用者。
posted @ 2018-10-17 15:09  奔腾的心01  阅读(111)  评论(0编辑  收藏  举报