SQL相关整理

串联多列值:
--concat(),参数:列或字符串,多个条件用逗号分开。
--示例
	select concat('列1', '列2') as concatStr  from table
if-else:
	--case表达式,使用方法,case when money>100 then '大于100' else '小于100' end
	--示例
	select case when column>100 then '大于100' else '小于100' end as test from table
随机返回若干行记录
	--mysql 随机:rand() 返回条数:limit
	select * from  table order By rand() limit 5  
	--DB2 随机:rand() 返回条数fetch first xx rows only,xx代表返回条数
	select * from table order by rand() fetch first 5 rows only
	-- SQL Server 随机newid()
	select top 5 * from table order by newid()
null值转换成实际值
	--coalesce(列,值)  将指定列的null值转换成指定值
	select coalesce(column,'值') from table --comm为指定table中的列
order by的排序
	--order by可以指定列名 也可以指定数值
	select * from table order by column_name
	select * from table order by column_number
	--column_number 具体的数字对应的返回列 从左向右数的第几列
多条件排序
	--排序列用逗号分开
	select * from table order by column1,column2
根据截取字符串排序
	--mysql,DB2...先使用substr(列,开始位置)截取字符串 再进行排序
	--SQL Server 使用substring(列,开始位置,截取长度)截取字符串 再进行排序
	select * from table order by substr(column,index) --mysql...
	select * from table order by substring(column,index,length) --SQL Server
对一列数据里面有null值的列排序
	--先将null单独提出来做为一列  然后在排序
	select column from 
	(select column , case when column is null then 0 else 1 end as columnIsNull  from table) table1 
	order by columnIsNull ,column 
	--除非数据库提供无需修改非null值数据的情况下方便的对null进行排序,否则一定得加一个辅助列
对逻辑条件进行排序
	--可以在order by 后面是用case 表达式
	select column from table order by case column='value' then column1 else column2 end 
UNION ALL 和 UNION
	--union all 和 union都是叠加两个行集的语句
	--区别:UNION ALL 将多个表中的行并入到一个结果集,UNION想当于针对UNION ALL的输出结果再执行一次DISTINCT
	--注:对于所有的集合运算来说,查询列的数量必须一致,且数据类型匹配
	select column1,column2 from table
	union all
	select column1,column2 from table2

	--返回数据
	--     column1       |        column2
	--  table.column1    |     table.column2 
	--  table.column1    |     table.column2 
	--  table1.column1   |     table1.column2 
	--  table1.column1   |     table1.column2 
连接查询

连接查询的两种方式

	select * from table1,table2 where table1.column=table2.column
	select * from table1 join table2 on table1.column=table2.column

上面两种风格都符合ANSI标准1,如果喜欢将连接逻辑写到from子句里,可以使用JION子句。在ON后面可以跟多条件关联

	select * from table1 
	join table2 on table1.column1=table2.column1 and table1.cloumn2=table2.cloumn2

  1. ANSI SQL:https://baike.baidu.com/item/ANSI SQL ↩︎

posted @ 2022-05-01 22:59  rr完美'诺言  阅读(2)  评论(0编辑  收藏  举报  来源