MySQL-基于其他datetime列修改datetime列
我花了很长时间才弄明白如何命名这个,但这里有一个解释 我有两张桌子 表1: 表2: 我要做的是从表#2中获取所有记录,匹配任何位于同一日期和同一日期时间内的表#1行,并通过从表#1中删除时间来修改结果集 一个例子是MySQL-基于其他datetime列修改datetime列,mysql,sql,Mysql,Sql,我花了很长时间才弄明白如何命名这个,但这里有一个解释 我有两张桌子 表1: 表2: 我要做的是从表#2中获取所有记录,匹配任何位于同一日期和同一日期时间内的表#1行,并通过从表#1中删除时间来修改结果集 一个例子是 --------------------------------------------------------- | table2id | start | end | --------------------------
---------------------------------------------------------
| table2id | start | end |
---------------------------------------------------------
| 3 | 2013-10-01 09:30:00 | 2013-10-01 17:00:00 |
---------------------------------------------------------
| 4 | 2013-10-02 09:00:00 | 2013-10-02 10:00:00 |
---------------------------------------------------------
| 4 | 2013-10-02 10:30:00 | 2013-10-02 17:00:00 |
---------------------------------------------------------
如何才能做到这一点?虽然我不能确定这种逻辑是否正确,但类似这样的逻辑可能与您所寻找的非常接近:
UPDATE tbl2
SET start = (SELECT end FROM tbl1 WHERE start = tbl2.start)
这两张表之间的关系还不十分清楚。但是,
id
显然没有。在您的示例中,唯一匹配的两个值是start
值。是什么将表1行与表2行联系起来的?这是开始时间吗?如果table#1
包含同一table#2
日期的多个时间间隔,该怎么办?我修改了我的问题,更清楚地说,在我的实际数据库中有另一个fk将这些表联系在一起(只是一个int列),除了没有其他东西将它们联系在一起。
SELECT Table2.id, Table1.end_date , Table2.end_date
FROM table1 AS Table1, table2 AS Table2
WHERE
Table1.start_date >= Table2.start_date
AND Table1.end_date <= Table2.end_date
UNION
SELECT Table2.id, Table2.start_date , Table1.start_date
FROM table1 AS Table1, table2 AS Table2
WHERE
Table1.start_date >= Table2.start_date
AND Table1.end_date <= Table2.end_date
UPDATE tbl2
SET start = (SELECT end FROM tbl1 WHERE start = tbl2.start)
SELECT Table2.id, Table1.end_date , Table2.end_date
FROM table1 AS Table1, table2 AS Table2
WHERE
Table1.start_date >= Table2.start_date
AND Table1.end_date <= Table2.end_date
UNION
SELECT Table2.id, Table2.start_date , Table1.start_date
FROM table1 AS Table1, table2 AS Table2
WHERE
Table1.start_date >= Table2.start_date
AND Table1.end_date <= Table2.end_date
---------------------------------------------------------
| table2id | start | end |
---------------------------------------------------------
| 3 | 2013-10-01 09:30:00 | 2013-10-01 17:00:00 |
| 4 | 2013-10-02 10:30:00 | 2013-10-02 17:00:00 |
| 3 | 2013-10-01 09:00:00 | 2013-10-01 09:00:00 | --> Extra Record
| 4 | 2013-10-02 09:00:00 | 2013-10-02 10:00:00 |