首页 > 解决方案 > 尝试合并两个不同的查询但没有成功

问题描述

我一直在尝试“合并”两个查询以获取具有最新价格的产品的最后更新日期,但没有成功。

看看这个:

我有 2 个不同的表: products_table 和 products_prices

products_table我有所有不同的产品,每次更改属性时,字段 last_update_date 也会更改。

如果我想获得产品的最后更新,我使用这个查询:

select a.item,a.last_update_date from products_table a inner join
(Select item, max(last_update_date) updates from products_table
group by item) b
on a.item=b.item --item is the product_id
and a.last_update_date=b.updates

另外,我有包含产品所有不同价格的表products_prices,如果我想获得产品的最新价格,我使用这个查询(按 request_id 过滤):

select * from products_prices a
where item_code = ''--Product_id
and request_id = (select max(request_id) from products_prices b where a.item_code=b.item_code);

问题是我不知道如何合并这两个查询以获得产品的最新更新和同一行中的最新价格

请你帮助我好吗?

标签: sql

解决方案


Select first_query.last_update_date, second_query.latest_price -- or whatever name it is
from
(select a.item, a.last_update_date from products_table a inner join
 (Select item, max(last_update_date) updates from products_table
 group by item) b
 on a.item=b.item --item is the product_id
 and a.last_update_date=b.updates) first_query, 
(select * from products_prices a
where item_code = ''--Product_id
and request_id = (select max(request_id) from products_prices b where a.item_code=b.item_code)) second_query
where
first_query.item = second_query.item_code;

推荐阅读