MySQL - 根据其他日期时间列修改日期时间列

时间:2013-10-01 12:21:48

标签: mysql sql

我很难搞清楚如何标题,但这是一个解释......

我有两张桌子

表#1:

--------------------------------------------------------------
| id  |        start        |         end         | duration |
-------------------------------------------------------------
|  1  | 2013-10-01 09:00:00 | 2013-10-01 09:30:00 |    30    |
-------------------------------------------------------------
|  2  | 2013-10-02 10:00:00 | 2013-10-02 10:30:00 |    30    |
--------------------------------------------------------------
| int |      datetime       |       datetime      |   int    |
--------------------------------------------------------------

表#2:

---------------------------------------------------
| id  |        start        |         end         |
---------------------------------------------------
|  3  | 2013-10-01 09:00:00 | 2013-10-01 17:00:00 |
---------------------------------------------------
|  4  | 2013-10-02 09:00:00 | 2013-10-02 17:00:00 |
---------------------------------------------------
| int |      datetime       |       datetime      |
---------------------------------------------------

我要做的是抓取表#2中的所有记录,匹配​​同一日期和同一日期时间内的任何表#1行,并通过删除表#1中的时间来修改结果集。 ..

示例结果将是......

---------------------------------------------------------
| 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 |
---------------------------------------------------------

如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

虽然我不能确定这个逻辑是否正确,但是这样的事情可能接近你正在寻找的东西:

UPDATE tbl2
SET start = (SELECT end FROM tbl1 WHERE start = tbl2.start)

这两个表格的关系并不十分清楚。但是,id 显然不是。您示例中仅匹配的两个值是start值。

答案 1 :(得分:0)

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

这可行,但会为您提供相同的startend的额外记录,您必须手动删除

---------------------------------------------------------
| 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 |