sql基本查询语句
查詢語句的五中字句:where(條件查詢),having(篩選),group by(分組),order by(排序),Limit(限制結(jié)果數(shù))
一 單表查詢
1、查詢指定列:select 列名 from 表名;
2、查詢?nèi)康牧校?strong>select * from 表名(*表示查詢表中的所有列)
3、去除重復(fù)行的數(shù)據(jù):select distinct 列名 from 表名
二 指定條件查詢 --where
查詢滿足條件的元組,一般通過where 語句實(shí)現(xiàn):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_' (%_指通配符,%可表示任意字符長度的字符,_表示單個(gè)字符)
5、空值:select * from lu_order where sku is null
6、多重條件邏輯運(yùn)算: select * from lu_order where sku=‘123’ and type=‘234’
三 order by使用
對(duì)查出的元組按指定的列(一個(gè)或多個(gè))按升序(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
將查詢結(jié)果按照某一列或多列進(jìn)行分組,值相等的為一組。一般是為了細(xì)化聚合函數(shù)的作用對(duì)象,若未進(jìn)行分組,則聚合函數(shù)是作用整個(gè)查詢結(jié)果;若分組了,則是每個(gè)組一個(gè)聚合函數(shù)作用。
常用的聚合函數(shù)有:
例如:
1、未分組,使用聚合函數(shù):select count(*) from lu_order--->計(jì)算出表中的所有元組數(shù)量
2、分組,使用聚合函數(shù):select ordernumber,count(*) from lu_order group by ordernumber--->ordernumber相同的為一組,得出每組中包含的元組數(shù)量
五 having子句
對(duì)分組后的結(jié)果進(jìn)行篩選,得出符合條件的組。注意:使用having則,查詢語句中必須使用了group by,否則會(huì)報(bào)錯(cuò)。
例如:
1、selectordernumber,count(*) from lu_order group by ordernumber having ordernumber in('1','2','3')--->ordernumber相同的為一組,得出每組中包含的元組數(shù)量
六 limit 字句
限制結(jié)果顯示的條數(shù)。
例如:
1、查詢前3行的數(shù)據(jù):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..稱為一個(gè)查詢塊,將一個(gè)查詢塊嵌套在另一個(gè)查詢塊的where或having子句中的就叫做嵌套查詢。
例如:
1、select ordernumber,sku,carrier from lu_order where ordernumber in(select ordernumber from lu_order_detail where ordernumber='1')
總結(jié)
- 上一篇: cmd命令行查看windows版本
- 下一篇: C#制作简易屏保