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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM