2

我很难弄清楚如何命名这个,但这里有一个解释......

我有两张桌子

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

如何做到这一点?

4

2 回答 2

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

this works but will give you an extra record with identical start and end that you have to manually delete

---------------------------------------------------------
| 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 |
于 2013-10-01T13:24:36.707 回答
0

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

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

这两个表之间的关系还不是很清楚。然而,id 显然没有。在您的示例中匹配的唯一两个值是这些start值。

于 2013-10-01T12:24:26.097 回答