mysql - 在 SQL : How to find two date values where the second one starts when the first one finishes? 中

标签 mysql sql

我正在尝试运行 SQL 查询来查找(并合并)两个日期条目,其中第二个日期在短期后开始,例如x,第一个日期结束后。

我的表中的数据(以及其他列)由两个日期列组成:添加和删除。我正在将这些条目与与原始表连接的表的副本进行比较

SELECT *
FROM table
LEFT JOIN table AS table2 ON table.id=table2.id AND table.removed<table2.added

通过这段代码,我可以获得所有不相互重叠的条目。 如何添加另一个标准来定义周期 x,它只给出 x 范围内的不重叠日期。所以类似“table2.removed - table.added <= x”。

如果满足上述条件,最好将这些行合并为一行。

编辑:示例表数据和结果

id          added                 removed
1           2009-03-11 23:27:58   2017-01-28 04:45:20
1           2017-01-31 05:07:10   2018-01-22 14:14:11

所以例如我想在 x < 5 天的时间内检测到这一行。

最佳答案

众所周知,日期函数是特定于数据库的。但这里是使用标准语法的想法:

SELECT *
FROM table t LEFT JOIN
     table t2
     ON t.id = t2.id AND
        t2.added > t.remove and
        t2.added < t.remove + interval '5 day'  -- whatever value you want

关于mysql - 在 SQL : How to find two date values where the second one starts when the first one finishes? 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56445923/

相关文章:

mysql - MySQL 中何时使用单引号、双引号和反引号

mysql - 外键约束的格式不正确 (MariaDB)

sql - 我需要删除小数点后的前导零

mysql - 简单的 MySQL 查询不选择所有数据?

PHP/MySQL - 创建唯一随机字符串的最佳方式?

mysql - 如果我有用户的纬度/经度位置,如何找出用户的邮政编码?需要帮助编写查询

sql - 如何仅在至少有一个 child 的情况下选择父行?

MySQL 查询 : output all players villages by coordinates

mysql - 将字符串添加到 select 语句以包含在结果集中

php - Mysql_query 不会将 id 复制到另一行