lg04551

导航

 

1、单表查询

单表查询的语法

select distinct 字段1,字段2 from 表名

  where 条件

  group by ffield

  having 筛选

   order by field

  limit限制条数

关键字的执行优先级

form

where

group by

having

distinct

order by

limit

1.找到表:from

2.拿着where指定的约束条件,去文件/表中取出一条条记录

3.将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组

4.将分组的结果进行having过滤

5.执行select

6.去重

7.将结果按条件排序:order by

8.限制结果的显示条数

简单查询

select * from emp 

去重

select distinct post form emp

通过四则运算

select name,salary*12 from emp

定义显示格式

as

concat()用于连接字符串

select concat('姓名:',name,'年薪:',salary*12) as annual_salary from emp

concat_ws()第一个参数为分隔串

select concat(':',name,salary*12) as annual_salary from emp

case

select( case when name='egon' then name when name='aa' then concat(name,'bb') else concat(name,'cc') end )as aa

from emp

where 约束条件

1、比较运算符:>,<,>=,<=,<>,!=

2、between 80 and 100值

3、in(80,90)值是80或90

4、like %表示任意多字符,_表示一个字符

5、逻辑运算符:在多个条件可以用逻辑运行符 and or not,如果是null 用is

group by

1、分组发生在where 之后,基于where 之后的记录而进行

2、分组指的是:将所有记录按某个相同字段进行归类

可以按照任意字段分组,但分组完毕后,比如group by  post 只能查看post字段,如果想查看得用聚合函数

GROUP BY关键字和GROUP_CONCAT()函数一起使用

SELECT post,GROUP_CONCAT(name) FROM employee GROUP BY post

聚合函数

count,max,min,avg,sum

Having过滤

having 发生在group by之后,因为having可以使用分组的字段,无法直接取到其它字段,可以使用聚合函数

select post,group_concat(name) from emp group by post having avg(salary) > 10000;

order by 

order by  默认升序, asc 升序,desc 降序

限制查询记录

limit

限制显示的条数

使用正则表达式查看所有员工中名字是jin开头,n或者g结果的员工信息

select * from employee where name regexp '^jin.*[gn]$';

 二、多表查询

笛卡尔积

select * from a ,b where a.id=b.id

内连接:

select * from a inner join b on a.id=b.id 

左连接:

select * from a left join b on a.id=b.id

右连接:

select* from a right join b on a.id=b.id

全连接

select * from a left join b on a.id=b.id

 union#去掉两次查询重复记录

select* from a right join b on a.id=b.id

posted on 2018-05-10 14:37  lg04551  阅读(70)  评论(0编辑  收藏  举报