【问题标题】:Finding field value pairs using SQL使用 SQL 查找字段值对
【发布时间】:2015-10-23 18:02:11
【问题描述】:

我很难将问题总结为一个漂亮、整洁的标题,因此标题可能会产生误导。情况是这样的

表 1 有一个 ID、一个问题和一个解决日期,因此预计某些日期将为空。 ID 也可以分配给多个问题。

表_1:

ID | Issue | Date
1  | a     | 1/1
2  | a     | 1/1
3  | b     | 
4  | c     | 1/2

我使用另一个表来更新这个表,所以对于这个例子,table_2 中的数据看起来像:

ID | Issue | Date
3  | b     | 1/3
1  | b     | 1/3

现在,我有一个查询,它将使用 table_2 信息更新 table_1 日期,基于 ID/问题配对,使用如下:

Update Table_1 tab1
left outer join Table_2 tab2
on tab1.id = tab2.id and tab1.issue = tab2.issue
set tab1.date = tab2.date

但是,有时表 2 的 ID/问题对在 table_1 中不是。我想将这些行插入 table_1,但我不确定如何执行此操作。

如果只有一个字段,比如 ID,我可以这样做:

insert into table_1 (ID, Issue, Date)
select ID, Issue, Date
from table_2 where table_2.ID not in (select ID from table_1)

我将如何为 ID/问题配对执行此操作? 使用上面的示例,我想将 table_2 中的以下行插入 table_1:

1 | b | 1/3

因为 1/b 的 ID/Issue 对存在于表 2 但不存在于表 1。

如何从表 2 中选择表 1 中不存在的 id/issue 对?

【问题讨论】:

标签: sql ms-access join


【解决方案1】:

您可以使用左外连接来执行此操作:

insert into table_1 (ID, Issue, Date)
select ID, Issue, Date
  from table_2 t2
  left outer join table_1 t1 on t1.ID = t2.ID and
                                t1.Issue = t2.Issue
 where t1.ID is null

这保证您获取 table_2 中的每一行,然后如果 table_1 中没有匹配项,则限制表 2 中的行。

【讨论】:

  • 谢谢丹尼尔,我以前从未想过这样做。非常感谢。
【解决方案2】:

一种方法是使用not exists:

insert into table_1 (ID, Issue, Date)
    select ID, Issue, Date
    from table_2
    where not exists (select 1
                      from table_1
                      where table_2.ID = table_1.ID and table_2.issue = table_1.issue
                     );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多