mysql - sql查询以获取最大日期比较当前记录日期的值

标签 mysql sql visual-foxpro

我有两张 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/

相关文章:

php - Magento 重新索引 + 目录页面问题

mysql - 我可以将这些嵌套查询作为一个查询运行吗?如何处理返回的信息?

foxpro - 如何将光标的数据写入txt文件中?视觉狐狸专业版

php - Laravel vagrant homestead连接xampp的mysql

mysql - 如何在持续交付中为 WordPress 执行高级数据库 merge ?

sql - 将 Postgres 查询结果合并到一个表中

C# 不喜欢 SQL JOINS

MySQL 查询 2 个表并从 2 列创建新列

visual-foxpro - Visual FoxPro 字符串到日期的转换

c# - FoxPro 到 C# : What best method between ODBC, OLE DB 或其他?