sql筆記五:高級查詢及通配符、排序分組

 

sql筆記五:高級查詢及通配符、排序分組
聯合查詢:
1、 內連接:join on
1.1語法一:
        格式:select 表.列名,表.列名 from 表1 join 表2 on 表1.列=表2.列 where 條件
1.2語法二:
        格式:select 表.列 from 表1,表2where表1.列=表2.列 and條件
2、 外連接:
2.1左外連接:left join on:以左表爲基準,查詢數據:
        格式:select 表.字段,表.字段 from 表1 left join 表2 on表1.列=表2.列 where 條件
2.2右外連接:right join on:以右表爲基準,查詢數據:
格式:select 表.字段,表.字段 from 表1 right join 表2 on表1.列=表2.列 where 條件
2.3全外連接:full join on:以右表爲基準,查詢數據:
格式:select 表.字段,表.字段 from 表1 full join 表2 on表1.列=表2.列 where 條件
3、 自連接:(必須起別名)
格式:select * from 表1 join 表1 on a.列=b.列 where 條件
說明:a,b是爲表1起的別名。
合併查詢:unio:
              格式:查詢語句 union 查詢語句
              實例:select id,name,tel,sex from score1
                      union
                      select id,name,tel,sex from score2
              說明:相同的列數,相同的數據類型,相同的順序、對應
嵌套查詢:in:
              格式:select 列名 from 表1 where 列名1 in(select 列名1 from 表2 where 條件)
 
模糊查詢:like:
              格式:select 列 from 表 where 列 like 條件
              實例:select * from score where name like ‘miller’
通配符:
              1、% 匹配任意字符:
                     實例:select * from score where name like ‘李%’
                     說明:從score表中查詢所有姓李的同學的數據,包含三個名字的。
              2、_ 匹配任意單個字符:
                     實例:select * from score where name like ‘李_’
                     說明:從score表中查詢所有姓李的同學的數據,只包含兩個名字的同學。
              3、[ ] 匹配包括括號內任意的單個字符:
                     實例:select * from score where name like ‘[李,張,王]%’
                     說明:從score表中查詢所有姓李,張,王的同學的數據
              4、[^] 或 [!] 匹配不包括括號內任意的單個字符:
                     實例:select * from score where name like ‘[^李,張,王]%’
                     說明:從score表中查詢所有不是姓李,張,王的同學的數據
排序:
1、 order by:
1.1    正序:order by 列asc (asc可以省略)
實例:select * from score order by id asc
1.2    倒序:order by 列desc
實例:select * from score order by id desc
2、 top number:顯示前n條數據:
實例:select top 2 * from score
說明:從score表中查詢前兩條數據
分組:group by:
              實例:select avg(score1) from score group by id
              說明:以id分組從score表中查詢score1的平均成績
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章