我对SQL有点麻烦,我使用MySQL。
我有两张桌子:
id address last_price m2 date_last_price
======================================================
id_1234 NY 100000 100 2017-11-27
id_5678 Madrid 90000 120 2017-11-27
id price date
===============================
id_1234 100000 2017-11-27
id_5678 90000 2017-11-27
id_1234 120000 2017-11-28
id_5678 90000 2017-11-28
id_1234 115000 2017-11-29
id_5678 95000 2017-11-29
我想在表1中插入/更新Table2中最后一个日期的价格。
结果必须如下
id address last_price m2 date_last_price
======================================================
id_1234 NY 115000 100 2017-11-29
id_5678 Madrid 95000 120 2017-11-29
你能帮我解决这个问题吗?
#Table 1
CREATE TABLE IF NOT EXISTS scrapp(
id varchar(50),
address varchar(50),
last_price int,
m2 int,
date_last_price date
);
INSERT INTO scrapp (id,address,last_price,m2,date_last_price)
VALUES('id_1234','NY',100000,100,'2017-11-27'),
('id_5678','Madrid',90000,120,'2017-11-27');
#Table 2
CREATE TABLE IF NOT EXISTS historic_price(
id varchar(50),
price int,
`date` date
);
INSERT INTO historic_price(id,price,date)
VALUES('id_1234',100000,'2017-11-27'),
('id_5678',90000,'2017-11-27'),
('id_1234',120000,'2017-11-28'),
('id_5678',90000,'2017-11-28'),
('id_1234',115000,'2017-11-29'),
('id_5678',95000,'2017-11-29');
答案 0 :(得分:0)
你可以在suquery上使用update with join获取最后一个价格
update scrapp
inner join (
select hp.id, hp.price, hp.date
from historic_price hp
inner join (
select id, max(date) max_date
from historic_price
group by historic_price.id
) t on t.id = hp.id and t.max_date = hp.date
) t2 on scrapp.id = t2.id
set scrapp.last_price = t2.price,
scrapp.date_last_price = t2.date