我有两张表,一张有交易记录(带日期)。另一个带有百分比和生效日期的百分比(假设 00:00:00)。在新的百分比生效之前,该百分比一直有效。我需要加入交易发生时生效的百分比。
transactions_table
event_date amount
2011-01-01 230
2011-02-18 194
2011-03-22 56
2011-04-30 874
percent_table
effective percent
2010-12-30 15
2011-03-05 25
2011-04-12 30
我要找的结果是:
event_date amount percent
2011-01-01 230 15
2011-02-18 194 15
2011-03-22 56 25
2011-04-30 874 30
我试过:
SELECT t.event_date, t.amount, p.percent
FROM transactions_table AS t
LEFT JOIN percent_table AS p ON t.event_date >= p.effective
ORDER BY `t`.`event_date` DESC LIMIT 0 , 30;
这给了我看似随机的百分比。在我看来,我需要获得最大日期 >= p.effective,而不仅仅是任何随机日期 >= p.effective。
我试过:
SELECT t.event_date, p.percent
FROM bedic_sixsummits_transactions AS t
LEFT JOIN bedic_sixsummits_percent AS p ON MAX(t.event_date >= p.effective)
ORDER BY `t`.`event_date` DESC LIMIT 0 , 30
但 MySQL 只是 mock 我的无力尝试。
我该怎么做?
最佳答案
SELECT t.event_date, t.amount, p.percent
FROM bedic_sixsummits_transactions AS t
LEFT JOIN bedic_sixsummits_percent AS p
ON p.effective =
( SELECT MAX( p2.effective ) FROM bedic_sixsummits_percent AS p2
WHERE p2.effective <= t.event_date
)
ORDER BY t.event_date DESC LIMIT 0 , 30
关于MySql JOIN 在最近的开始日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10986520/