SQL经典实例笔记

前言

本文是根据我阅读的书籍SQL经典实例而写的笔记,只记载我觉得有价值的内容

第一章:检索记录

在Where字句中使用别名

--错误实例
select p as PartNumber from Product where PartNumber='LMKHS'

在Where字句中使用别名,结果报错,原因是因为SQL的执行顺序是

  1. From
  2. Where
  3. Select

可以看到Where比Select先执行,所以别名是Select里面定义的,Where里面肯定用不了

解决办法

如果想在Where中使用以下内容的时候,可以使用内嵌视图

  1. 聚合函数 : 例如min(),max(),sum(),avg()
  2. 标量子查询 : 必须而且只能返回1 行1列的结果的select查询
  3. 窗口函数
  4. 别名 : 本例的as
--内嵌视图如下
select * from(
	select p as PartNumber from Product
) temp where PartNumber='LMKHS'

拼接字段数据

例如,我这个表查询语句和结果如下

select Title,Genre from Movie

SQLServer使用+即可完成拼接,Mysql需要使用concat函数,结果如下

select Title+' 是 '+Genre as msg from Movie

Select语句中使用条件逻辑 case when then

select Title,Genre,case when Price = 0 then '零' when Price > 0 then '非零' else '负数' end as status  from Movie

Order By中使用Case When

select name,sal from Movie order by case when sal > 10 then sal asc else sal desc end

把NULL值替换为实际值 coalesce函数

我以前都是直接找到字段 is Null 的然后直接update了,这个函数也行,用也可以

select coalesce(Genre,'音乐家')  from Movie
update Movie set Genre=coalesce(Genre,'音乐家')  where ID = 1

第三章:多表查询

union和union all,慎用union

希望两个表进行拼接的时候常常会用到union和union all,区别是显而易见的,union去除了重复数据,union all会显示所有的数据,不管你重复与否,那么问题来了,使用union的时候是先执行了union all,然后再执行了一次distinct去重,例如

select distinct name from(
    select name from A union all select name from B
)

在数据量大的时候,执行distinct是非常不好的,所以数据比较大的时候慎重使用union

原文地址:https://www.cnblogs.com/yunquan/p/12061451.html