MySql JOIN 在最近的开始日期?

标签 mysql sql

我有两张表,一张有交易记录(带日期)。另一个带有百分比和生效日期的百分比(假设 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/

相关文章:

php - 如何根据主表中的id从另一个表中选择两个附加列?

php - 从 mysql 到 PDO 的转换

php - 我可以单独从服务器端 PHP 填充 "Google Charts"吗?

php - 根据用户事件更新数据库表

sql - 合并来自 T-SQL 的 XML

java - Jtable 未填充一条记录

MySQL 不处理 ENUM 类型错误

php - MYSQL内连接只显示一条记录

sql - 如何从 JSONB 列中提取数据

sql - 计算一个月的条目数