【问题标题】:How to join table A to B to find all the entries in A whose intervals contain entries in B?如何将表 A 连接到 B 以查找 A 中间隔包含 B 中的条目的所有条目?
【发布时间】:2014-05-01 21:49:47
【问题描述】:

我正在比较两个表 AB 的日志条目间隔,即对于给定用户,表中的每条记录是第一个日志条目,然后是另一个日志条目,如下所示:

+--------+----------+--------+-----------+--------+
| userID |  date1   | logID1 |   date2   | logID2 |
+--------+----------+--------+-----------+--------+
|    235 | 1/3/2013 |     45 | 1/7/2013  |     48 |
|    235 | 4/6/2013 |     64 | 4/12/2013 |     73 |
|    462 | 1/4/2013 |     40 | 1/16/2013 |     50 |
+--------+----------+--------+-----------+--------+

我想构建一个连接查询,将A 中的每条记录链接到基于userIDB 中的所有记录,其中A 在任一日期都包含B

a.date1<=b.date1, a.date2>=b.date2

或 ID:

a.logID1<=b.logID1, a.logID2>=b.logID2

我想返回A中的所有记录,不管B中是否有包含区间。

乍一看,这似乎可行:

select * from a
left join b
on
a.userID=b.userID
where
(a.date1<=b.date1 or a.logID1<=b.logID1)
and
(a.date2>=b.date2 or a.logID2>=b.logID2)
or
b.userID is null

但问题是,如果A 中有一条记录在B 中有匹配的userIDA 记录不包含B 记录,则会发生连接但记录会被 WHERE 条件过滤掉,所以A 记录不会出现在结果中。

如果我尝试通过将 WHERE 条件移至 JOIN 子句来解决此问题,如下所示:

select * from a
left join b
on
a.userID=b.userID
and
(a.date1<=b.date1 or a.logID1<=b.logID1)
and
(a.date2>=b.date2 or a.logID2>=b.logID2)

然后我收到此错误消息:

JOIN expression not supported.

我假设这意味着 Access 不能在 JOIN 条件中包含嵌套的 OR 条件。

我可以做些什么来返回A 的列表,并在适用的情况下加入到其中包含的B

【问题讨论】:

    标签: sql ms-access ms-access-2010


    【解决方案1】:

    如果您想要a 中的所有记录,则将条件放在on 子句中。 where 有奇怪的效果。所以试试:

    select *
    from a left join
         b
         on a.userID = b.userID and
            (a.date1<=b.date1 or a.logID1<=b.logID1)
            (a.date2>=b.date2 or a.logID2>=b.logID2);
    

    【讨论】:

    • 正如我在问题中提到的,这给出了JOIN expression not supported 错误;我认为 Access 不允许在 JOIN 子句中进行嵌套 OR 操作。
    • 没关系,这确实有效。错误消息是由于我的原始查询中的别名不一致造成的。
    • @sigil 。 . .呸。 Access 有很多奇怪的限制,但我认为这不是其中之一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多