跳至主要內容

复杂查询汇总

soulballad总结文字总结文字总结约 534 字大约 2 分钟

1. 两表关联取B表满足条件的第一条数据

例如有两个表goods和prices,商品表中的一条商品信息会对应价格表中的多条价格信息,现在要根据商品表查询其商品对应的可用最新的价格,即要满足价格的生效日期必须在商品上市之前,如果有多个价格,就选取最后生效的那个价格。

goods:商品表

序号商品名称上市日期
1iphone62015-10-01
2iphone62016-08-01
3iphone62017-09-01

prices:价格表

序号商品名称单价生效日期
6iphone665002015-09-15
7iphone660002016-06-15
8iphone658002017-08-15

希望得到的结果是:

货物序号商品名称上市日期单价单价生效日期
1iphone62015-10-0165002015-09-15
2iphone62016-08-0160002016-06-15
3iphone62017-09-0158002017-08-15

常见问题:只是通过left join进行外联查询,例如我现在要查询“上市日期”= 2017-09-01,“商品名称”=“iphone6”的商品对应的单价如果仅仅使用select B.price from goods A left join prices B on A.goods_name = B.goods_name and A.launch_date > B.effective_date,这样查出来会有三个价格符合条件,现在要选择最新的一个价格,还需要在初步筛选的结果中选取生效日期最大的数据,最后查询sql如下:

select A.*, B.price, B.effective_date from goods A left join prices B 
on A.goods_name = B.goods_name and A.launch_date > B.effective_date
and B.effective_date = (
    select max(effective_date) from prices where A.goods_name = goods_name and A.launch_date > effective_date
    )
order by A.id

2. 查询不同区间数量

分区域查询满足条件的数量值:
select t1.p1 as num1, t2.p2 as num2, t3.p3 as num3 from
(select count(BASICPRICE) as p1 from product where BASICPRICE>=40.0 and BASICPRICE <=440.0 ) t1 INNER JOIN
(select count(BASICPRICE) as p2 from product where BASICPRICE>=440.1 and BASICPRICE <=840.0 ) t2 INNER JOIN
(select count(BASICPRICE) as p3 from product where BASICPRICE>=840.1 and BASICPRICE <=1240.0 ) t3

参考:

上次编辑于:
贡献者: soulballad