复杂查询汇总
约 534 字大约 2 分钟
1. 两表关联取B表满足条件的第一条数据
例如有两个表goods和prices,商品表中的一条商品信息会对应价格表中的多条价格信息,现在要根据商品表查询其商品对应的可用最新的价格,即要满足价格的生效日期必须在商品上市之前,如果有多个价格,就选取最后生效的那个价格。
goods:商品表
| 序号 | 商品名称 | 上市日期 |
|---|---|---|
| 1 | iphone6 | 2015-10-01 |
| 2 | iphone6 | 2016-08-01 |
| 3 | iphone6 | 2017-09-01 |
prices:价格表
| 序号 | 商品名称 | 单价 | 生效日期 |
|---|---|---|---|
| 6 | iphone6 | 6500 | 2015-09-15 |
| 7 | iphone6 | 6000 | 2016-06-15 |
| 8 | iphone6 | 5800 | 2017-08-15 |
希望得到的结果是:
| 货物序号 | 商品名称 | 上市日期 | 单价 | 单价生效日期 |
|---|---|---|---|---|
| 1 | iphone6 | 2015-10-01 | 6500 | 2015-09-15 |
| 2 | iphone6 | 2016-08-01 | 6000 | 2016-06-15 |
| 3 | iphone6 | 2017-09-01 | 5800 | 2017-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
参考: