sql基本查询语句
查詢語句的五中字句:where(條件查詢),having(篩選),group by(分組),order by(排序),Limit(限制結果數)
一 單表查詢
1、查詢指定列:select 列名 from 表名;
2、查詢全部的列:select * from 表名(*表示查詢表中的所有列)
3、去除重復行的數據:select distinct 列名 from 表名
二 指定條件查詢 --where
查詢滿足條件的元組,一般通過where 語句實現:select 列名 from 表名 where 條件
例子:
1、比較:select * from lu_order where sku ='123'
2、確定范圍 :select * from lu_order where stage between 20 and 30
3、確定集合:select * from lu_order where sku in('123','1232','1232323')
4、字符匹配:select *from lu_order where sku like '%123_' (%_指通配符,%可表示任意字符長度的字符,_表示單個字符)
5、空值:select * from lu_order where sku is null
6、多重條件邏輯運算: select * from lu_order where sku=‘123’ and type=‘234’
三 order by使用
對查出的元組按指定的列(一個或多個)按升序(asc)或降序(desc)排序
1、升序:select * from lu_order order by id asc
2、降序:select * from lu_order where sku=‘122’ order by sku desc
四 group by
將查詢結果按照某一列或多列進行分組,值相等的為一組。一般是為了細化聚合函數的作用對象,若未進行分組,則聚合函數是作用整個查詢結果;若分組了,則是每個組一個聚合函數作用。
常用的聚合函數有:
例如:
1、未分組,使用聚合函數:select count(*) from lu_order--->計算出表中的所有元組數量
2、分組,使用聚合函數:select ordernumber,count(*) from lu_order group by ordernumber--->ordernumber相同的為一組,得出每組中包含的元組數量
五 having子句
對分組后的結果進行篩選,得出符合條件的組。注意:使用having則,查詢語句中必須使用了group by,否則會報錯。
例如:
1、selectordernumber,count(*) from lu_order group by ordernumber having ordernumber in('1','2','3')--->ordernumber相同的為一組,得出每組中包含的元組數量
六 limit 字句
限制結果顯示的條數。
例如:
1、查詢前3行的數據:select* from lu_order limit 0,3
七 多表查詢
表跟表之間通過某些條件,連接起來。
1、自然連接:select a.*,b.* from lu_order a,lu_order_detail b where a.ordernumber=b.ordernumber
2、自身連接:select a.*,b.* from lu_order a,lu_order bwhere a.ordernumber=b.ordernumber
3、左連接:select a.*,b.* from lu_order left out join lu_order_detail
4、右連接:select a.*,b.* from lu_orderright out joinlu_order_detail
八 嵌套查詢
在select-from-where..稱為一個查詢塊,將一個查詢塊嵌套在另一個查詢塊的where或having子句中的就叫做嵌套查詢。
例如:
1、select ordernumber,sku,carrier from lu_order where ordernumber in(select ordernumber from lu_order_detail where ordernumber='1')
總結
- 上一篇: cmd命令行查看windows版本
- 下一篇: C#制作简易屏保