有两张表table1与table2内容如下: 
table1表 
________________________ 
ClassId      TableName 
1                x    
2                x1    
2                x5  
3                t2  
3                y1  
________________________ table2表 
________________________ 
ClassId      TableName 
1                t 
2                x1 
3                ta 
4                y1 
2                ta 
________________________ 
问:如果将存在table2不存在table1的记录,插入到table1表中?如果我想要的结果是: 
_______________________ 
classid      tablename 
1              t 
3              ta 
4              y1 
2              ta 
_______________________ 
并且插入table1中,使table1变成:
classid      tablename
1         t
1         x
2         x1
3         t2
3         ta
3         y1
3         y2
4         y1
该怎么做?

解决方案 »

  1.   

    ....
    重复发帖了吧
    insert into table1(classid,tablename)
    select a.classid ,a.tablename 
    from table2 a left join table1 b
       on a.classid=b.classid 
        and a.tablename=b.tablename
    where b.classid is null
      

  2.   

    这样不行啊。。为什么提示
    服务器: 消息 207,级别 16,状态 3,行 1
    列名 'tablename' 无效。
      

  3.   

    insert into table1(classid,tablename)
    select classid,tablename from table2
    where not exists
    (select 1 from table1 where table1.classid = table2.classid and table1.tablename=table2.tablename)
      

  4.   


    确定列名tablename是不是正确
      

  5.   

    insert into table1(classid,tablename) select classid,tablename from table2 where not exists(select 1 from table1 where table1 .classid=table2.classid )