【问题标题】:selecting row from one table and insert into other table从一个表中选择行并插入到另一个表中
【发布时间】:2013-07-05 09:15:06
【问题描述】:

从table1中选择table2中不存在的行并插入到table2中

喜欢

图片

id  type    name
502  1      summer.gif

SEO图片

id      idimage ... ...
1000    501     ... ...

现在我想从Images 表中选择所有id 与idimage SEOImages 表不匹配的行,并将这些行插入SEOImages 表中。

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    方法:

    Insert into Table2
    select A,B,C,....
      from Table1
     Where Not Exists (select * 
                     from table2 
                    where Your_where_clause)
    

    示例:

    SQLFiddelDemo

    Create table Images(id int,
                        type int,
                        name varchar(20));
    Create table SEOImages(id int,
                           idimage int);
    
    insert into Images values(502,1,'Summer.gif');
    insert into Images values(503,1,'Summer.gif');
    insert into Images values(504,1,'Summer.gif');
    insert into SEOImages values(1000,501);
    insert into SEOImages values(1000,502);
    insert into SEOImages values(1000,503);
    
    insert into SEOImages
    select 1000,id
      from Images I
     where not exists (select * 
                      from SEOImages
                      where idimage =I.id);
    

    【讨论】:

      【解决方案2】:
      INSERT INTO SeoImages
      (IdImage)
      SELECT ID
      FROM Images
      WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages)
      

      【讨论】:

        【解决方案3】:

        查询:

        SELECT * FROM Images
          WHERE id NOT IN (SELECT idimage FROM SEOImages)
        

        应该从图片中找出那些在 SEOImages 中没有对应 ID 的行,假设它们都是同一类型。

        或者,使用 JOIN:

        SELECT i.* FROM Images i
            LEFT OUTER JOIN SEOImages s on i.id = s.imageId
        WHERE s.imageId IS NULL
        

        【讨论】:

          【解决方案4】:
          INSERT INTO SEOImages
          SELECT *
          FROM Images
          WHERE NOT EXISTS (SELECT 1 
                           FROM Images t1, SEOImages t2 
                           WHERE t1.id=t2.id) ;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-30
            • 1970-01-01
            • 2014-02-17
            相关资源
            最近更新 更多