Mysql sql查询以获取与当前记录日期比较的最长日期的值
我有两张桌子 表1有字段 childid, ondate, points 1 31/01/2017 50 1 28/02/2017 77 1 31/03/2017 25 childid, programid, fromdate 1 1 01/01/2017 1 2 01/03/2017 表2有字段 childid, ondate, points 1 31/01/2017 50 1 28/02/2017 77 1 31/03/2017 25 childid, programid, fromdate 1 1 01/01/2017 1 2 01/03/2017 表2规定该儿童在2017年1月1日至2017年3月1日期间在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 sql查询以获取与当前记录日期比较的最长日期的值,mysql,sql,visual-foxpro,Mysql,Sql,Visual Foxpro,我有两张桌子 表1有字段 childid, ondate, points 1 31/01/2017 50 1 28/02/2017 77 1 31/03/2017 25 childid, programid, fromdate 1 1 01/01/2017 1 2 01/03/2017 表2有字段 child
SELECT t1.childid, t1.ondate, t1.points, t2.programid
FROM table1 as t1
INNER JOIN table2 as t2 on t1.chilid = t2.childid
and t2.fromdate <= t1.ondate;
只需使用t2.fromdate连接两个表即可尝试以下操作:
SELECT t1.childid, t1.ondate, t1.points, t2.programid
FROM table1 as t1
INNER JOIN table2 as t2 on t1.chilid = t2.childid
and t2.fromdate <= t1.ondate;
只需使用t2.fromdate将这两个表连接起来即可。注意:这个答案是针对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;
这保证在表1中的任何给定日期,每个孩子只有一个程序。注意:这个答案是针对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;
这保证了在表1中的任何给定日期,每个孩子只有一个程序。如果查询需要与VFP兼容,那么它可以是:
Select tb1.*, tb2.programid ;
FROM table1 tb1 ;
inner Join (;
SELECT *, ;
NVL((Select Min(fromdate) ;
from table2 t1;
WHERE t1.childid=t2.childid And ;
t1.fromdate > t2.fromdate),Date(9999,12,31)) As toDate ;
FROM table2 t2 ;
) tb2 ;
ON tb1.childid = tb2.childid And ;
tb1.ondate >= tb2.fromdate And ;
tb1.ondate < tb2.toDate
如果查询需要与VFP兼容,则可以是:
Select tb1.*, tb2.programid ;
FROM table1 tb1 ;
inner Join (;
SELECT *, ;
NVL((Select Min(fromdate) ;
from table2 t1;
WHERE t1.childid=t2.childid And ;
t1.fromdate > t2.fromdate),Date(9999,12,31)) As toDate ;
FROM table2 t2 ;
) tb2 ;
ON tb1.childid = tb2.childid And ;
tb1.ondate >= tb2.fromdate And ;
tb1.ondate < tb2.toDate
@Santosh所以不要使用“停止使用以数据为中心、面向对象、过程化的编程语言”@草莓。我甚至没有注意到Foxpro标签。谢谢,它对我有用。我在上面的查询中只添加了orderbyt1.ondatedesc@Strawberry,限制1在MSSQL中也不起作用。所以也不要使用MSSQL?LOL.@Santosh所以不要使用“停止使用以数据为中心、面向对象、过程化的编程语言”@草莓。我甚至没有注意到Foxpro标签。谢谢,它对我有用。我在上面的查询中只添加了orderbyt1.ondatedesc@Strawberry,限制1在MSSQL中也不起作用。所以也不要使用MSSQL?英雄联盟