sql查询语句

select *from table where ......  #先执行的是from   后执行的是 where

查询有很多种,select 、where  、group by、 having、oder by、limit 、regexp、like、

1.where

  #筛选id大于3 小于6 

  select * from table where id > =3 and id < =6;

  #筛选出 id 等于 1 或者  等于2 或者等于3 

  select * from table where id = 1 or id = 2 or id = 3;

  #筛选出 id 等于 1 或者  等于2 或者等于3 

  select *from table where id in (1,2,3);

  #筛选出id在3到6之间的

  select *from table where id betweem 3 and 6;

  #筛选 id不在 元组中的数的

  select *from table where id not in (1,3);

  #筛选 含有名字含有a的

  select *from table  where name like '%a%';

  #筛选名字中为4个字符的

  select *from table  where name like '____'; 

  select *from table  where char_length(name) = 4;

  #查询为空的

  select * from table where name is null

#  补充:

  mysql  对大小写不敏感的,%意味着 0或多个字符,而 _意味着1个字符

  char_length()  可以查询数据的长度

2.group by  # 顾名思义,是用来 分组

  select  * from table group by post ;#按部门分

  在没有开启严格模式是可以执行的

  设置严格模式  set  global sql_mode = ‘strict_trans_tables,only_full_group_by'

  分组不能拿单独的数据了

  select post from table group by post;

  #获取部门的最高薪资,

  select post ,max(salary) from table group by post;

  select post as '部门' ,max(salary) as '薪资' from table group by post;

  最先 min  平均  avg  总和  sum

  #统计部门人数

  select port ,count(id)  from table group by port

  #获取分组后,字段的值

  select post ,group_concat(name,':',salary) from table group by post;

  #注意: 可以拼接 group_concat(name,salary ,'_haha');

  !!!cancat  不分组的时候用的,默认起始为一组,

   as  可以给表临时起名

  #select  t1.id ,t1.name from bjadjkabdjah as t1 ;   当表名字很长的时候

  #查询年薪  12  薪

  select name ,salary* 12 from table ;  可以数字运算   

  !!!!!! 分组注意点: where group by 同时出现,group by 要在where 后面;

    聚合函数,只能在from前面;

  #统计 各部门 年龄在30以上,的员工平均薪资;

  select post ,avg(salary) from table where age >30 group by post;

3.having #分组之后的筛选条件

  #having 的语法和where 一样,只不过是在分组后的过滤操作,即having 是可以直接用聚合函数的

  select port avg(salary) from table where age > 30 group by post having avg(salary) > 1000;

4.dictinct 去重

  #一定是完全一样的数据,才能去重,不要忽视主键 id 的存在;

  select dintinct id,age from table;

  select dintinct age from table;

5. order by#排序

  select *from table  order by salary #默认是升序

  #升序  asc  降序   desc order by 可以添加多个;

  select *from table order by desc ,salary asc;

6.limit #限制展示的数据,分页;

  select *from table limit 3;#只显示3条;

  select *from table limit(n,m) #起始位置n,开始取m条数据;

7.正则

  select *from where name regexp '^j.*(n|y)$'   #以j开头,n或者y结尾的

连表

  四种,inner join    left join ,right join , union

  inner 只显示都存在的

  left  显示 左边

  right  显示右边

  union 显示 两边

子查询 就是我们解决问题的步骤,

  select *from emp where dep_id in (select id from dep where name = '技术' or name = '人力资源')

总结:

  表的查询结果,可以作为其他表的查询条件;

  也可以通过别名的方式把它作为一个虚拟表很其他表关联