sql高級命令

sql高級命令


在一次面試中,sql語句基本寫不上來,平時就是增刪改查,對於一個特殊一定的sql語法沒有接觸,網上找一些資料,自己彙總一下。
stu

id name age score
1 dawei 20 18
2 liming 23 58
3 zhanghua 22 65
4 lucy 18 88
5 xiaohua 22 78

– 選取前n條記錄
select top 3 * from stu

– 列之間的數學運算 ( mysql中的加號 + ,就是用來做數學運算的 )
select age + score as result from stu

– 字符串的拼接
select concat(“a” , “b”, “c”) from dual ==> “abc”

集合運算(交集、並集等)
– union 並集,不重複
select * from t1 union select * from t2
– union all 並集,重複
select * from t1 union all select * from t2
– intersect 交集,相同部分
select * from t1 intersect select * from t2
– except 減集 ,除相同部分
select * from t1 except select * from t2

– ifnull 處理內容爲null的結果
select ifnull(num,0) as num from t1
得到的結果中,如果有null,則替換爲0

– 插入一列時,先判斷是否插入過,沒有插入過再插入
INSERT INTO order (order_id,group_id,created_at)
SELECT
#{OrderId},
#{GroupId},
#{CreateAt}
FROM DUAL
WHERE not EXISTS ( SELECT 1 FROM car_order_ids WHERE order_id = #{OrderId} and group_id = #{GroupId} )
判斷傳入的數據是否存在表中
dual 表,是一個虛擬表,爲了保證格式的正確而存在的,沒有實際存儲的內容

– exists,判斷一個子句是否返回了至少一個值
select * from t1 where exists (select 1 from t2 where name = “tom”)
如果從t2表中查到了tom,結果返回1,exists後面的select語句返回值,這個exists就返回true,前面的select* 就生效

先寫到這,肯定還會補充的

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