我有两个表,一个有事务(带日期)。另一个用百分比和日期表示它生效的百分比(假设为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只是嘲笑我的微弱尝试。
我该怎么做?
答案 0 :(得分:1)
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
答案 1 :(得分:1)
更简单,没有子查询:
SELECT event_date, amount, MAX(_percent) as _percent
FROM transactions_table
LEFT JOIN percent_table p1 ON event_date >= effective
GROUP BY event_date, amount
ORDER BY event_date;
http://sqlfiddle.com/#!3/e8ca3/17/0
请注意,由于涉及的业务模式,这是可能的。如果你不想检索percent_table的其他字段,它将不再合适:/