初级水平:
- 参考内容:《深入浅出SQL》《SQL必知必会》
- 涉及内容:对表内数据进行简单的查询
里面的内容无关痛痒,主要是记录格式用。
1. 选取列
#选取某一列
select cust_name from customers
#选取某两列,用逗号隔开
select cust_name,cust_address from customers
#选取全部列
#但是并不推荐这种方法,cust_id列有索引(聚集索引和辅助索引),当我们用where 条件通过其索引过滤掉一部分记录时,查询会先走辅助索引,如果我们只需要一部分列,但选择用select*,就会获取不需要的数据,并且运行过程中首先会通过辅助索引过滤数据然后使用聚集索引获取所有的列,这样就会多一次cust_id树查询,速度会慢很多。当表结构发生改变的时候,对代码的影响也会比较大。
select * from customers
#选取列中不重复值
select distinct cust_city from customers
2. 排序
#升序,是默认的选项
select cust_name from customers
order by cust_name
#升序,写出条件
select cust_name from customers
order by cust_name ASC
#降序
select cust_name from customers
order by cust_name DESC
#多列混合,ASC/DESC只对身前的一列有用
select cust_name from customers
order by cust_name ASC, cust_address DESC
3. 限制结果
#SQL server 中是用top来限制结果的
# 排在前三的
select top 3 cust_name from customers
order by cust_name DESC
#显示出并列第三的
select top 3 with cust_name from customers
order by cust_name DESC
#mySQL是用limit来限制结果的,先来组无序向
#第六行到第十行
select cust_name from customers
limit 5,5
#前2行
select cust_name from customers
limit 2
#有序向的前两行
select cust_name from customers
order by cust_name DESC
limit 2
4. 过滤条件
查询条件 | 谓词 |
---|---|
比较 | =,>,>=,<,<=,<>(!=) |
确定范围 | between and , not between and |
确定集合 | in,not in |
字符匹配 | like,not like |
空值 | is null ,is not null |
多重条件 | and,or |
#进行比较
#列出价格小于10美元的所有产品
select prod_name,prod_price from products
where prod_price < 10
#范围查询(可以替换用and,并且and优先级高于or)
#价格在5到10美元之间的所有产品
select prod_name,prod_price from products
where prod_price between 5 and 10
--等同
select prod_name,prod_price from products
where prod_price>=5 and prod_price<=10
#确定集合(作用同or)
select prod_name,prod_price from products
where vend_id in(1002,1003)
#空值查询
#我们要区分空值和空字符(" "),空字符有实际意义,计算的时候会被统计进去。
select cust_id from customers
where cust_email is null
5. 通配符
符号 | 意义 |
---|---|
_ | 匹配一个字符 |
% | 匹配0个或多个字符 |
#通配符处理时间长,如果其他的操作符能够达到同样目的,就不要使用通配符。不要将其置于搜索模式开始处。
#匹配一个字符
select prod_id,prod_name from products
where prod_name like '_ton anvil'
#匹配不定个字符
select prod_id,prod_name from products
where prod_name like '% anvil %'
6. 聚集函数
#均值avg
select avg(prod_price) as avg_price from products
#count(*)统计全部行数
select count(*)as num_cust from customers
#count(column)统计该列有数据的总数
select count(cust_email) as num_cust from customers
#最大值max
select max(prod_price) as max_price from products
#最小值min
select min(prod_price) as min_price from products
#总和sum
select sum(prod_price) as sum_price from products
7. 分组
#分组依据列,聚类函数不能放在group by里
select vend_id ,count(*) as num_prods from products
group by vend_id
#条件分组,有having一定要有group by
select vend_id,count(*) as num_prods from products
where prod_price >= 10
group by vend_id
having count(*) >= 2
8. 子查询
#普通的子查询,in来表示
select cust_id from orders
where order_num in (
select order_num from orderitems
where prod_id='TNT2')
#基于计算的子查询
select cust_name,
cust_state,
(select count(*) from orders
where orders.cust_id=customers.cust_id) as orders
from customers
order by cust_name