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的平均成绩
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章