2013-07-05 53 views

回答

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

1使用(不)存在,而不是(未)在 – Sam

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 
2
INSERT INTO SeoImages 
(IdImage) 
SELECT ID 
FROM Images 
WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages) 
1
INSERT INTO SEOImages 
SELECT * 
FROM Images 
WHERE NOT EXISTS (SELECT 1 
       FROM Images t1, SEOImages t2 
       WHERE t1.id=t2.id) ; 
相關問題