我在oracle数据库中有两个表
表1说明了包含字段(id, name)
的table1
记录例如
###############
id | name
1 | Chair
2 | Table
3 | Bed
###############
和表2将table2表示为字段(id, table1_id, date, price)
##############################
id |table1_id| date | price
1 | 1 | 2013-09-09 | 500
2 | 1 | 2013-08-09 | 300
3 | 2 | 2013-09-09 | 5100
4 | 2 | 2013-08-09 | 5000
5 | 3 | 2013-09-09 | 10500
################################
我想要实现的是从表2中检索所有物品的最新价格
SQL的结果应该是
##############################
id |table1_id| date | price
1 | 1 | 2013-09-09 | 500
3 | 2 | 2013-09-09 | 5100
5 | 3 | 2013-09-09 | 10500
################################
我可以通过以下查询
在mysql中运行 SELECT t2.id, t1.id, t1.name, t2.date, t2.price
FROM table1 t1 JOIN table2 t2
ON (t1.id = t2.table1_id
AND t2.id = (
SELECT id
FROM table2
WHERE table1_id = t1.id
ORDER BY table2.date DESC
LIMIT 1
));
但它在ORACLE中不起作用,这里我需要一个可以在两个服务器上运行并进行微小修改的查询
答案 0 :(得分:2)
你可以试试这个(在MySQL和Oracle中都很好):
select t2.id, t2.table1_id, t2.dat, t2.price
from table1 t1 join table2 t2 on (t1.id = t2.table1_id)
join (select table1_id, max(dat) max_date
from table2 group by table1_id) tmax
on (tmax.table1_id = t2.table1_id and tmax.max_date = t2.dat);
如果table2中有多个价格,此查询可能会为同一个table1_id和date返回多行,如下所示:
##############################
id |table1_id| date | price
1 | 1 | 2013-09-09 | 500
2 | 1 | 2013-09-09 | 300
可以更改查询以仅为每个table1_id检索1行,但应该有一些额外的要求(在上面的示例中要选择哪一行)
如果不重要,那么你可以试试这个:
select max(t2.id) as id, t2.table1_id, t2.dat, max(t2.price) as price
from table1 t1 join table2 t2 on (t1.id = t2.table1_id)
join (select table1_id, max(dat) max_date
from table2 group by table1_id) tmax
on (tmax.table1_id = t2.table1_id and tmax.max_date = t2.dat)
group by t2.table1_id, t2.dat;
答案 1 :(得分:1)
您可以使用GROUP BY
来尝试此操作,因为除了产品ID(已经在table2中)之外,您没有从table1中检索产品名称
SELECT id,table1_id,max(date),price
FROM table2
GROUP BY id,table1_id,price
答案 2 :(得分:1)
this就是你想要的:
select t2.id,t2.table1_id,t1.name,t2.pricedate,t2.price
from table1 t1
join
(
select id,table1_id, pricedate,price, row_number() over (partition by table1_id order by pricedate desc) rn
from table2
) t2
on t1.id = t2.table1_id
where t2.rn = 1