使用SQL

时间:2015-10-23 18:02:12

标签: sql ms-access join

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

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

TABLE_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

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

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会在table_1中具有的ID /问题对。我想将这些行插入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

因为表2中存在1 / b的ID /问题对,但不存在表1。

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

2 个答案:

答案 0 :(得分: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中的行。

答案 1 :(得分:0)

一种方法是使用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 );

static void Main(string[] args)
    {
        ProjectContext pc = getProjCtxt();
        ColumnNames fldList = new ColumnNames();

        var q = from ColumnNames.colInfo fld in fldList.impFields
                where fld.CustomField == false
                select fld;

        Console.WriteLine(q.Count());

        foreach(ColumnNames.colInfo dynField in q){
            pc.Load(pc.Projects, p => p.Include(pj => pj[dynField.FieldName]));
        }
        pc.Load(pc.Projects, p => p.Include(pj => pj.IncludeCustomFields));
        pc.ExecuteQuery();
    }