SQL常用select语句汇总

----------------------------------------写在前面----------------------------------------

适用情形

MySQL、SQLServer、Excel…

书写规范,以MySQL为例
  • 支持中文
  • 不区分大小写(有的区分)
  • 字符串要用单引号,如’string’
  • 数字也可以加单引号,如’4’
  • 木有撤销功能,所以操作前记得备份
  • 符号一律在英文格式下输入
特殊符号
  • ‘N’

    • 表示以Unicode格式存入数据库,使用2个字节存储字符
    • 如N’string’
  • ‘@’

    • 标识本地的变量或者参数
  • ‘#’

    • 标识临时表或过程
  • ‘##’

    • 标识全局临时对象

-----------------------------------简单查询----------------------------------------

1. 条件查询

	--多字段、多条件全查
	select 字段1,字段2 as 别名 from 表名 where 条件1 and/or 条件2    --as关键字可以省略
	select * from users where ojbk = 'you'
	
	--区间查询
	select * from 表名 where 字段 between 范围1 and 范围2 
	--包括边界值,not between不包括
	select * from 表名 where 字段 in('元素1','元素2','元素3')
	
	--模糊查询
	select * from 表名 where 字段 like '%关键字%' or '%关键字' or '关键字%'
	
	--空值查询
	select * from 表名 where 字段=''
	select * from 表名 where 字段 is Null

2. 聚合函数

	select max(字段) from 表名
	select min(字段) from 表名
	select avg(字段) from 表名
	select sum(字段) as 别名 from 表名
	select count(字段) as Totalcount from 表名
	
	/*聚合函数常与以下的分组函数一同使用*/

3. 排序、分组、分页

	select * from 表名 order by 字段 asc
	
	select 字段1,聚合函数(字段2) from 表名 group by 字段
	--分组条件查询
	select 字段1,聚合函数(字段2) from 表名 group by 字段 having 组条件
	--having兼容where
	
	--分页查询
	select * from 表名 limit int类型数据1,int类型数据2
	/*数据1指从下标为?的行开始(从0计),数据2指当前分页显示?条数据
	只有一个数据时,则当前分页从0行开始,显示?条数据*/
	
	--简单的组合查询(顺序不可调动)
	select * from 表名 where 条件1 and 模糊条件2 order by 字段 desc limit 0,4
	--子条件查询(将一个查询结果当做条件使用)
	select * from 表名 where 字段=(select 字段聚合函数 from 表名)
	select a,b,c from a where a IN (select d from b)

4. 多表联合

	--建立关联表
	/*表1和表2有相同字段的,如字段1,需标注表1.字段1或表2.字段1,否则可省略表名*/
	
	select 表1.字段1,表2.字段1,字段2,字段3, from 表1,表2 where 表1.字段1=表2.字段1
	
	--左连接查询
	select * from 表1 left join 表2 on 表1.字段1=表2.字段1
	/*以左表为准,右表数据匹配,无匹配数据则过滤,左表以Null填充*/
	
	--右连接查询
	select * from 表1 right join 表2 on 表1.字段1=表2.字段1
	
	--内连接查询
	select * from 表1 inner join 表2 on 表1.字段1=表2.字段1
	
	--全连接
	select * from 表1 FULL JOIN 表2 on 表1.字段1=表2.字段1
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值