幾條常用的sql查詢語句

2021-09-25 02:56:41 字數 2509 閱讀 3520

select * from table where type = 1;
以上是一條最簡單的sql條件查詢語句,那我們如果有2個type需要同時查詢呢?

我們可以這樣寫:

select * from table where type = 1 or type = 2;
如果,我們查出的結果是多個,且需要排序呢?

關鍵字 order by

-- desc 降序,asc 公升序,預設公升序

select * from table where type = 1 or type = 2 order by aid desc;

那麼,如果是3個type,4個type...甚至n個type呢,豈不是sql會非常長?

我們可以稍微改下:

select * from table where type in (1,2,3...);  

-- 注意後面的省略號只是寫在偽**中表示可以有多個

其實相比於or操作,in不僅僅是讓sql語句更簡潔,在大資料庫查詢時效能上更有優勢,or的效率為o(n),而in的效率為o(log2n),所有當基數越大,in的執行效率相對於or來說越有優勢。

正常有索引的時候可能感覺並不明顯,但是當aid無索引時,執行效率立馬就體現出來了...

不信的朋友可以試試100萬以上的資料表,過濾無索引字段查詢100條以上記錄,or的執行時間至少是in的幾十倍以上...

然後, 我們再來看看新的需求,有兩張表tablea, tableb, tablea中有字段bid,用於關聯tableb表,我們需要過濾tableb的name欄位包含「n」字母,進而查詢出tablea表的資料...

於是sql變成這樣:

select a.* from tablea a 

where a.bid

in (

select b.id from tableb b where b.name like "%n%"

);

exists

然而,從執行效率來說,exists是由於in的,所以上面的sql,我們可以這樣寫:

select a.* from tablea a 

where

exists (

select b.id from tableb b where b.name like "%n%" and a.bid = b.id

);

另外,如果我們使用in時,如果有2層以上的情況,如:

select a.* from tablea a 

where a.bid

in (

select b.id from tableb b

where b.cid

in (

select c.id from tablec c where c.name like "%n%"));

可以嘗試下,哪怕每個表的id和關聯id都有索引,但是,仍然是100萬+資料表,這個查詢會非常慢,此時,我們可以使用join(其實兩層的時候也建議用join,雖然寫起來麻煩一些,但是效率更高啊)...

join

select a.* from tablea a 

join tableb b on a.bid = b.id

join tablec c on b.cid = c.id

where c.name like "%n%";

這樣就將三張表關聯起來了,如果有需要,還可以4張,5張表關聯...

join還有inner join, left join, right join,full join四種用法,上面的寫法join其實預設就是inner join...

你一定注意到了,通過join,我們不僅可以用於替換in操作,還可以用於查詢多個表的字段,如:

select a.name, b.name, c.name from tablea a 

join tableb b on a.bid = b.id

join tablec c on b.cid = c.id

where c.name like "%n%";

當然,對賬期間還用到了set @、group by、like、not like以及count、sum、contains等,由於時間關係,就暫不記錄了。

準備準備,下班回家過年了v

提前祝大家豬年快樂,豬事大吉

幾條經典的SQL語句

sql select into b from a where 1 1 說明 拷貝表 拷貝資料,源表名 a 目標表名 b sql insert into b a,b,c select d,e,f from b sql select a.title,a.username,b.adddate from t...

mysql 常用幾條語句

1 設關聯式資料庫中乙個表s的結構為 s sn,cn,grade 其中sn為學生名,cn為課程名,二者均為字元型 grade為成績,數值型,取值範圍0 100。若要更正王二的化學成績為85分,則可用 update s set grade 85 where sn 王二 and cn 化學 update...

常用的sql查詢語句

一 簡單查詢語句 1.檢視表結構 sql desc emp 2.查詢所有列 sql select from emp 3.查詢指定列 sql select empmo,ename,mgr from emp sql select distinct mgr from emp 只顯示結果不同的項 4.查詢指...