1. 程式人生 > >總結的幾個常用的sql例子

總結的幾個常用的sql例子

1, 利用case  when  then    end 進行資料分類統計。

     用法1:select  case when type=1  then '數學'  when type=2 then '英語'   when type=3 then '語文'  else '其他' end  askemu,count(*)  from`kechengbiao` group by when type=1then '數學'  when type=2 then '英語'   when type=3 then '語文'  else '其他'end

   用法2:select case type when 1 then '數學'  when 2  then  '英語'  when 3  then  '語文'  else  '其他'  end as  kemu,count(*) from `kechengbiao` group by case type when 1 then '數學'  when 2  then  '英語'  when 3  then  '語文'  else  '其他'  end

2, 利用 union all 同時查詢多個表把查出的資料當成一個表再按照需求查詢,一般用於排序

     需求:表user1與表user2都有一個欄位 time 獲取兩個表最新註冊的10條資料

  select *  from  ( select id,name,age,time,1 as type from user1 union all  select id name age,time 2 from user2 ) as tmp order by  time

desc limit 10

注:user1與user2查詢的欄位數目要一樣,即使查詢的兩個表的欄位不一樣,可以給我兩個表加一個標識欄位例如上sql中的type,查詢出來的結果中有type,值為1的就是user1的資料,值為2就是user2的資料。

3,利用 case when  then else  end 進行排序

    需求:表user中的欄位state值為1表示未開始,2表示進行中,3表示結束。要查詢出資料要求進行中的資料靠前,未開始的再中間,結束的資料最後,其餘按照時間排序

 select id,name,time,case when state=1 then 11 when state=2 then 10  when state=3 then 12 else 13 end as sor from user order by sor asc,time desc

4,利用concat來比較兩個相同欄位表的不同資料

表a,表b有相同的欄位time,uid,from_uid,is_read 但是現在需要找出兩個表這些欄位不同的資料

思路:把這麼多欄位可以當成一個欄位來看待,利用concat連線把欄位資料拼在一起取一個別名m。

:由於m不是表中的欄位不能出現在where中做條件,可以在having中做條件

select concat(time,uid,type,from_uid,is_read) as  m   from  hao_wodehuifu  HAVING m not in(select concat(time,uid,type,from_uid,is_read) as m  from  heixionghao_wodehuifu )

5,利用group by來查詢一個表中不同的資料

表A中有age,sex,kecheng這三個欄位現在需要統計在年齡,性別,課程上不同的人數

select count(*) from A group by age,sex,kecheng

6,當需要複雜的分類查詢的時候,可以用case when then  else  end 配合group by來進行發咋的分組查詢,但是如果查詢需要連表查詢的時候分組查詢很慢,我們可以用union all來代替分組

例子1:select case when (u.time>100 and u.time<200) and (r.time>233 and r.time<500) then 'a' 

when  (u.time>333 and u.time<666) and (r.time>123 and r.time<359) then 'b' else 'c' end as `type`,  count(distinct u.uid) from A as u inner join B as r on u.uid=r.uid group bywhen (u.time>100 and u.time<200) and (r.time>233 and r.time<500) then 'a' 

when  (u.time>333 and u.time<666) and (r.time>123 and r.time<359) then 'b' else 'c' end

上述例子可以改為:

例子2:select count(distinct uid) from A where time>100 and time<200 and uid in(

select uid from B where time>233 and time<500)

union all

select count(distinct uid) from A where time>333 and time<666and uid in(

select uid from B where time>123and time<359)

例子1與例子2的查詢結果一樣但是比例子2的慢很多

7,在一些條件下可以使用子查詢來代替連表查詢會更快

當一個表與自身連線的時候,我們可以使用子查詢來代替內聯查詢會更快

例子1:select a1.* from A as a1 inner join A as a2 ON a1.uid=a2.uid where a1.time>222 and a1.time<333 and a2.time>666 and a2.time<888;

這個例子可以改寫為:

例子2:select * from A where time>222 and time<333 and uid in(select uid from A where time>666 and time<888);

例子1與例子2查詢的結果都是一樣的