左加入 MAX(DATE)
Left Join on MAX(DATE)
我有 2 tables:交易 (a) 和价格 (b)。我想从 table b 中检索在交易日期有效的价格。
Table a包含文章交易历史:
Store_type、日期、文章、...
Table b 包含商品价格的历史记录:
Store_type、日期、文章、价格
目前我有这个:
Select
a.Store_type,
a.Date
a.Article,
(select b.price
from PRICES b
where b.Store_type = a.Store_type
and b.Article = a.Article
and b.Date = (select max(c.date)
from PRICES c
where c.Store_type = a.Store_type
and c.Article = a.Article
and c.date <= a.date)) AS ART_PRICE
from TRANSACTIONS a
它工作得很好,但由于双重子查询,它似乎需要很长时间。
可以用 LEFT JOIN 做同样的事情吗?
可以尝试使用以下查询吗?
SELECT a.Store_type, a.Date, a.Article, b.Price
FROM TRANSACTIONS a
LEFT JOIN PRICES b ON a.Store_type = b.Store_type
AND a.Article = b.Article
AND b.Date = (SELECT MAX (c.Date)
FROM PRICES c
WHERE a.Store_type = c.Store_Type
AND a.Article = c.Article
AND c.Date <= a.Date)
它还有一个子查询,用于检索最大日期。
我有 2 tables:交易 (a) 和价格 (b)。我想从 table b 中检索在交易日期有效的价格。
Table a包含文章交易历史: Store_type、日期、文章、...
Table b 包含商品价格的历史记录: Store_type、日期、文章、价格
目前我有这个:
Select
a.Store_type,
a.Date
a.Article,
(select b.price
from PRICES b
where b.Store_type = a.Store_type
and b.Article = a.Article
and b.Date = (select max(c.date)
from PRICES c
where c.Store_type = a.Store_type
and c.Article = a.Article
and c.date <= a.date)) AS ART_PRICE
from TRANSACTIONS a
它工作得很好,但由于双重子查询,它似乎需要很长时间。 可以用 LEFT JOIN 做同样的事情吗?
可以尝试使用以下查询吗?
SELECT a.Store_type, a.Date, a.Article, b.Price
FROM TRANSACTIONS a
LEFT JOIN PRICES b ON a.Store_type = b.Store_type
AND a.Article = b.Article
AND b.Date = (SELECT MAX (c.Date)
FROM PRICES c
WHERE a.Store_type = c.Store_Type
AND a.Article = c.Article
AND c.Date <= a.Date)
它还有一个子查询,用于检索最大日期。