2012-06-11 30 views
1

我有兩個表,其中一個交易(與日期)。另一個具有百分比並記錄生效的百分比(假設00:00:00)。百分比保持有效,直到新百分比生效。我需要加入交易發生時有效的百分比。MySql加入最近的start_date?

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的只是嘲笑我的愚蠢的嘗試。

我該怎麼做?

回答

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 
+0

謝謝,這個工作很好! – MikeP

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的其他字段,它將不再適用:/

+0

這工作得很好。在這個查詢中,我們只需要找到有效的百分比,所以它是適當的。這仍然適用於不同的ORDER BY值(例如金額)嗎?這會比子查詢方法更快嗎? – MikeP

+0

只有百分比隨時間增加,此方法纔有效。當前寫入的查詢獲取事件發生前和發生日期之前的所有生效日期的最大百分比值,這與獲取最新適用值不同。 –

+0

謝謝,我明白了。再次感謝Fred! – MikeP