【数据库】2查询

来源:互联网 发布:知乎live的入口 编辑:程序博客网 时间:2024/06/07 08:15

七查询

1select

1where2group by3order by4limit

1)表:select * from 表;
2)字段:select 字段1,字段2 from 表;
3)指定记录:where
select * \字段\distinct 字段 from 表 where 字段 查询条件

查询条件
between and 之间
in(‘a’,‘b’,‘c’)之内
not in
like _(一个) %(多个)模糊
is null 空值
and or and优于or

4)分组:group by
select id,count(*) as Total from 表 group by id;
select * from 表 group by id,name;
*过滤分组 having:只满足条件才显示
select id,f_name as names from 表 group by id having f_name>1;
*分组总数 with rollup:结果最后一行显示总数,不能同时使用order by
select id,count(*) as Total from 表 group by id with rollup;
5)排序:order by asc升序 desc降序
select *from 表 order by 字段 desc;
select *from 表 order by 字段1 desc,字段2 asc;
6)分组排序

例:订单价格大于100的订单号和总订单价格
select num,sum(quantity*item_price) as total from 表
group by num having sum(quantity*item_price)>=100
order by total;

7)限制:limit
sleect * from 表 limit 4;
sleect * from 表 limit 4,3;从第五条数据开始3条数据
sleect * from 表 limit 4 offset 3;同上

2连接查询

正常连接
select 表1.表1字段1,表1.表1字段2,表2.表2字段1,表2.表2字段2
from 表1,表2 where 表1.id=表2.id;
1)内连接:inner join ……on 性能比where好
select 表1.表1字段1,表1.表1字段2,表2.表2字段1,表2.表2字段2
from 表1 inner join表2 on 表1.id=表2.id;
2)自连接 特殊的内连接,两表在物理上为同一张表,逻辑上为两张

例:id=a1
select f1.id,f1.name from 表1 as f1,表1 as f2 where f1.id=f2.id and f2.id=‘a1’;
查询的是两张表,防止二义表,对表用了别名,第一次f1,第二次f2

3)外链接
①左连接:left join
select cus.c_id,order.o_num from cus left join order on cus.c_id=order.c_id;
②右连接:left join
select cus.c_id,order.o_num from cus right join order on cus.c_id=order.c_id;
4)复合条件连接查询

例1:两表中查询ID=10001的客户订单
select cus.c_id,order.o_num from cus right join order on cus.c_id=order.c_id and cus_id=10001;
例2:内连接排序
select sup.s_id,f_name from fruits inner join suppliers on sup_id=fruit_id order by fruits.s_id;

3子查询

1)any、some
b1:1,5,13,27;
b2:6,14,11,20;
返回b2所有列,然后b1的值比较,b1>b2

select 列b1 from 表b1 where b1>any(select 列b2 from 表b2)→13,27

2)all
b1:1,5,13,27;
b2:6,14,11,20;
返回b1表中比b2表所有值都大的值

select 列b1 from 表b1 where b1>all(select 列b2 from 表b2)→27

3)exists,not exists
查询sup表中是否存在s_id=107的供应商

select * from fruits where exists(select s_name from sup where s_id=107);

查询sup表中是否存在s_id=107,如果存在,查询f_fruits表中f_frice大于10.20记录

select * from fruits where f_price>10.20 and exists(select s_name from sup where s_id=107);

4)in,not in
ordertems表中查询f_id为co的订单号,查询该用户c_id

select c_id from orders where o_num in(select o_num from orderitimes where f_id=’co’);

5)比较运算符
在sup查询s_city=’Tianjing’的供应商s_id,在fruits表中查询所有该供应商提供的水果种类

select s_id f_name from fruits where s_id=或<>非供应商 (select s1.s_id from sup as s1 where s1.s_city=’Tianjing’);

6)合并查询 union(删除重复)union all(不删除重复)
价格小于9,s_id=101、103

select s_id,f_name,f_price from fruits where f_price <9.0 union all
select s_id,f_name,f_price from fruits where s_id in(101,103);

7)优化:最好用连接不用子查询
8)问题:没有找到查询记录:like ‘%e’可能数据以空格结尾