我有两张 table 表 1 有字段
childid, ondate, points 1 31/01/2017 50 1 28/02/2017 77 1 31/03/2017 25
Table2 有字段
childid, programid, fromdate 1 1 01/01/2017 1 2 01/03/2017
表 2 指定 child 从 01/01/2017 到 01/03/2017 在 programid 1 中,之后他在 programid 2 中。 所以我的结果应该是这样的
childid, ondate, points Programid 1 31/01/2017 50 1 1 28/02/2017 77 1 1 31/03/2017 25 2
请帮忙
最佳答案
注意:这个答案是针对 MySQL 的。
这有点棘手。我认为相关子查询是最简单的方法:
select t1.*,
(select t2.programid
from table2 t2
where t2.childid = t1.childid and
t2.fromdate <= t1.ondate
order by t1.ondate desc
limit 1
) as programid
from table1 t1
order by t1.ondate desc;
这保证在 table1
中的任何给定日期只有一个节目(每个 child )。
关于mysql - sql查询以获取最大日期比较当前记录日期的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46767615/