数据库的查询⽅法
简单查询:
⼀、投影
select * from 表名
select 列1,列2... from 表名
select distinct 列名 from 表名
⼆、筛选
select top 数字列|* from 表名
(⼀)等值与不等值
select * from 表名 where 列名=值
select中distinct
select * from 表名 where 列名!=值
select * from 表名 where 列名>值
select * from 表名 where 列名<;值
select * from 表名 where 列名>=值
select * from 表名 where 列名<=值
(⼆)多条件与范围
select * from 表名 where 条件1 and|or 条件2 ...
select * from 表名 where between ... and ...
select * from 表名 where 列 in (值列表)
(三)模糊查询 like % _
select * from 表名 where 列 like '%_....'
三、排序
select * from 表名 where 条件 order by 列名 ASC|DESC,列名 ASC|DESC
四、分组:
统计函数(聚合函数)
count(), max(), min(), sum(), avg()
count()统计总⾏数
count(*)得到所有的⾏数
count(列)得到该列中所有⾮null个数。
select COUNT(*) from car where Brand='b003'
max(列) 这⼀列的最⼤,min(列)这⼀列的最⼩
select min(price) from car
sum(列)这⼀列的和,avg(列)这⼀列的平均
select AVG(price) from car
group by ...
2.⼀旦使⽤group by分组了,则select和from中间就不能⽤*,只能包含两类东西⼀类是:group by 后⾯的列名,另⼀类是统计函数select Oil,avg(price) from Car group by oil
对于统计函数⽣成的列,默认是⽆列名,可以通过下⾯的⽅法指定列名。
select Oil as 油耗,COUNT(*) as 数量,avg(price) 均价 from Car group by oil
having后⾯⼀般跟得是统计函数。它⽤来对分组后的数据进⼀步筛选。
复杂查询:
⼀、连接查询
把多个表的列合在⼀个界⾯视图中。
思想:1.⽣成笛卡尔积。2.对笛卡尔积进⾏筛选。3.选择列进⾏显⽰。
select 表1.列1,表1.列2,表2.列1,表2.列2…… from 表1,表2 where 表1.列=表2.列
select * from 表1
join 表2 on 表1.列=表2.列
join 表3 on 表2.列=表3.列
左连(left join),右连(right join),全连(full join)
⼆、联合查询
把多个表的⾏合在⼀个界⾯视图中。
⽤union把两个查询组合在⼀起。要求是这两个查询的列要⼀⼀对应。
三、⼦查询(嵌套查询)
(⼀)⽆关⼦查询:
⾄少是两层查询,在外层查询的⾥⾯再写查询。
⾥层查询为外层查询提供查询的中间内容。