SQL -- 查询

单表查询:

基础查询语句:

  select 列名

  from 表名

  where 条件     

  group by 列名

  order by 列名    

  having   //查询第二条件,常跟group by 配合使用

  limit 个数

where子句比较运算符:

=   !=   >=  <=

like   not like  

is null   

between...and...    

in(值1,值2)      

group by:

 按列不同值分组,常与avg、sum等聚合函数一起使用

order by:

 排序,默认升序。desc降序   asc升序

通配符:

  • %     一个或多个字符  
  • _      单个字符

  如果需要查询包含%或_(即%和_不作为通配符),使用escape,例如:

  select * from tb1 where addr like '%/%g%' escape '/'  查找包含%g的(escape后的/也可以换成其他字符)

  select * from tb1 where addr like '%a%g%' escape 'a' (a后的%不作为通配符)

where和having: 

  •   where无法跟合计函数一起使用,如:

        where sum(cnt) > 3   错误

        having sum(cnt) > 3  正确

  •   where作用于视图和表,having作用于组
  •   where在分组和聚集之前,选取输入行(它控制哪些行进入聚集运算);having在分组和聚集之后,选择分组的行
  •   having一般跟在group by之后,执行记录组选择的一部分来工作的,where则是执行所有数据来工作的

distinct:

  查询出所选列中,值不同的行

  select distinct 列1,列2 from 表名  //distinct对后面的列1,列2均有效

  select 列1,列2,列3 from 表名 group by 列1,列2,列3

  In most cases, a DISTINCT clause can be considered as a special case of GROUP BY. For example, the following two queries are equivalent: (distinct子句是group by的特例,以下两个语句等效)

select distinct c1, c2, c3 from t1
select c1, c2, c3 from t1 group by c1, c2, c3
 
 

子查询:

多表查询:

 

内连接

左连接

右连接

外连接

合并查询:

猜你喜欢

转载自www.cnblogs.com/xiaochongc/p/11330709.html