join on max mysql_Left Join on MAX(DATE)

问题

I have 2 tables: Transactions (a) and Prices (b). I want to retrieve the price from table b that is valid on the transaction date.

Table a contains a history of article transactions:

Store_type, Date, Article, ...

Table b contains a history of article prices:

Store_type, Date, Article, price

Currently i have this:

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

It works just fine but it seems to take very long because of the double subquery.

Can the same be done with a LEFT JOIN?

回答1:

Can try using the below query ?

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)

It still has one subquery though, used to retrieve the maximum date.

来源:https://stackoverflow.com/questions/32265830/left-join-on-maxdate

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值