1.SQL中出现顺序
where > group by > having > order by > limit
※ having 对单独字段进行筛选时,select查询列中必须出现该字段
having对某个字段的聚合函数做筛选时,select查询列中不必出现该字段
具体参考 这篇文章的5c) 关于sql语句优先级的理解
2.distinct注意事项
①对字段进行操作时,必须在开头 :select distinct col1,col2 from table;
②对字段的聚合函数进行操作时,则不需要放在开头:select col1,count(distinct(col2)) form table;
③distinct用在所有检测列前,作用于所有检测列,不单独对某列起作用:
select distinct name,id from table; --实际筛选的是name+id两列
3.模糊匹配 like
①包含的匹配模式:_, %,[],[^]
分别表示:单个字符,多个字符,匹配方括号内任一元素,不包含方括号内的任一元素
②MySQL字母匹配时不区分大小写,如需区分,可使用关键字binary
select id from t where name= binary "Mary"
/* binary放在等号右边才可以用到索引,放左边不能,待探究验证 */
③模糊查询前模糊会导致索引失效,影响性能 :
解决办法:
a: like "%ABC" 这种匹配词在最末尾时,
翻转函数+建立翻转列索引:使前模糊变为后模糊,走翻转函数索引
create index reverse_t_name on t(reverse(name));
select name from t where reverse(name) like reverse("%ABC");
b:like "%ABC%" 这种匹配词位置不固定时,
使用 locate, position, instr, find_in_set等方法 (待完善)可参考: MySQL前模糊查询索引优化
4.union 与·union all 都在求并集
①union会筛出重复行,相当于distinct了一下;
union all 会保留重复行;
②对结果集排序时,order by只能出现一次且出现在最后(的子句)。ps:子句的子句中可以随意出现
select * from table where id between 10 and 20 # 这个子句不在最后,不可以加order by
union
select * from table where age =9 order by id # 此处的order by是对union后的整个结果集排序
5.各种join
①各种join的不同
- INNER JOIN:如果表中有至少一个匹配,则返回行
- LEFT JOIN:即使右表中没有匹配,也从左表返回所有的行
- RIGHT JOIN:即使左表中没有匹配,也从右表返回所有的行
- FULL JOIN:只要其中一个表中存在匹配,则返回行
②使用using:使用连接查询时,如果两表连接字段名相同,可用using省略表名前缀或别名
select * from a join b on a.column_c = b.column_c
简化后
select * from a join b using(column_c)
6.where语句优化
待完善,参考:第二部分SQL优化