SQL雜記

SQL是Structured Query Language,其指令分爲四個子集,如下圖:


圖片來源:https://www.geeksforgeeks.org/sql-ddl-dml-tcl-dcl/

其中DML用於查詢,DDL用於創建、插入、刪除等操作,這兩者構成了SQL的基礎。DCL和TCL一般傾向於數據庫&服務器的操作,DCL用於用戶授權,TCL中文成爲事務控制語言,事務(Transaction)是一系列相關的SQL語句組成的動作單元,用於完成某個固定操作。CSDN上有一篇詳解:https://blog.csdn.net/G090909/article/details/53153218,以及Geeksforgeeks上的英文版:https://www.geeksforgeeks.org/sql-transactions/

§ Constraints (5種約束)
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type of data that can be stored in a particular column in a table using constraints.
<https://www.geeksforgeeks.org/sql-constraints/> ---- include examples how to use it
-NOT NULL
-UNIQUE
-PRIMARY KEY
-FOREIGN KEY
-CHECK
-DEFAULT

§ Triggers
A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated.
<https://www.geeksforgeeks.org/sql-trigger-student-database/>

§ Functions
Aggregate functions: count(), sum(), avg(), min(), max(), first(), last()
Scalar functions: ucase(), lcase(), mid(), len(), round(), now(), format()
Mathematical functions: sqrt(), pi(), square(), round(), ceiling(), floor()
Listagg:
AGG function in DBMS is used to aggregate strings from data in columns in a database table. Aus <https://www.geeksforgeeks.org/sql-listagg/>
Date functions (a loooooot):
https://www.geeksforgeeks.org/sql-date-functions-set-1/
https://www.geeksforgeeks.org/sql-date-functions-set-2/
Conditional Expression: case(CASE WHEN ** THEN ** END), decode, coalesce, greatest, ifnull, in, least, nullif
https://www.geeksforgeeks.org/sql-conditional-expressions/
String functions (many)
Numeric functions (many)

§ View

§ 常見query
§§ like 和通配符(wildcard)(%, _, [])
通配符搜索只能用於文本字段,非文本數據型字段不能使用。Eg WHERE name LIKE 'Fish%'
§§ group by
§§ order by
§§ union
§§ join
§§ having v.s. where: where語句用在分組之前的篩選,having用在分組之後的篩選,having中可以用合計函數,where中就不行。使用where的地方可以用having替代
……

§ 理解SQL難點,就兩點:
第一點:數學映射join(一對一,一對多,多對多);
第二點:就是SQL的執行順序;
其他:至於底層的東西,先把SQL數據跑起來,跑正確再說

§ 執行順序
https://mp.weixin.qq.com/s?__biz=MzIyNzA5MjM5NA==&mid=2647852899&idx=1&sn=b2dcfe42a09fea4f7507bf7117e05d32&scene=19#wechat_redirect


如圖所示,我們書寫的時候,要注意關鍵字的順序,比如select,from寫完後,要先where,然後group by,然後having,order by永遠是放在最後面。但是實際執行的時候,系統先跳過select,從from開始、加載需要處理的表格,然後where進行初步過濾,注意這個過濾是在分組前進行過濾,然後通過group by進行分組,再利用having進行分組後的過濾、篩選滿足條件的組,然後纔是select及其之後的語句。理解了這一點,也就很容易理解一些語法規定了,例如:where條件中不能跟聚合函數,而having後面可以;執行順序where>聚合函數(sum,min,max,avg,count)>having,order by是最後的顯示結果進行排序,必須放於最後,等等規定。
<https://zhuanlan.zhihu.com/p/39246170> --很好的實踐總結文,推薦閱讀

另,推薦《SQL必知必會》(簡單的入門書),以及知乎專欄《有關SQL》https://zhuanlan.zhihu.com/c_180683105 。其中有一篇介紹大數據生態鏈各階段入門書的文章,可以作爲自學索引 https://zhuanlan.zhihu.com/p/63963773

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章