1. 程式人生 > 其它 >【寫MySQL語句中遇到的不熟練處記錄】

【寫MySQL語句中遇到的不熟練處記錄】

按從 Z 到 A 的順序顯示結果

字串預設就是按字典順序
Z 到 A 的排序:order by cust_name desc

先按XX排序,再按XX排序

先按顧客 ID 對結果進行排序,再按訂單日期倒序排列。直接在order by中寫多個欄位即可。
 select cust_id,order_num from Orders order by cust_id, order_date desc;

order by 的使用在where 之後

包含 toy 一詞

where prod_desc like '%toy%';

不包含 toy 一詞

where prod_desc not like '%toy%';

包含 toy 和 carrots

where prod_desc like '%toy%' and prod_desc like '%carrots%' ;

返回大寫字母 upper()

字母大寫:upper(字串)

取前n個字元並進行拼接

字串的擷取:substring(字串,起始位置(從1開始),擷取字元數)
字串的拼接:concat(字串1,字串2,字串3,...)
concat(substring(cust_name,1,2),substring(cust_city,1,3))

返回日期的一部分---date_format(日期,'%Y%m%d)

select order_num,order_date
from Orders
where date_format(order_date,'%Y-%m')='2020-01'
order by order_date
或者
where month(order_date) = 1 and year(order_date) = 2020

典型函式

最大值---max()
最小值---min()
平均值---avg()
總值 ---sum()
總數 ---count()

group by 和 having

where---過濾過濾指定的行
having--過濾分組,與group by連用
where條件語句後面不能加聚合函式(分組函式)
having 不能單獨使用,必須和group by 聯合使用

select order_num
from OrderItems
group by order_num
having sum(quantity)>=100
order by order_num

join 和 union

join---連線表,對列操作
union--連線表,對行操作。
union--將兩個表做行拼接,同時自動刪除重複的行。
union all---將兩個表做行拼接,保留重複的行。

只用一條select語句,那就用or不用union了