从一个表中选择行并插入另一个表

时间:2013-07-05 09:15:06

标签: sql sql-server tsql

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

图片

id  type    name
502  1      summer.gif

SEOImages

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

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

4 个答案:

答案 0 :(得分:2)

方法:

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);

答案 1 :(得分:2)

INSERT INTO SeoImages
(IdImage)
SELECT ID
FROM Images
WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages)

答案 2 :(得分:1)

查询:

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

答案 3 :(得分:1)

INSERT INTO SEOImages
SELECT *
FROM Images
WHERE NOT EXISTS (SELECT 1 
                 FROM Images t1, SEOImages t2 
                 WHERE t1.id=t2.id) ;