選擇行和表2中插入它從一個表中選擇行並插入到其他表的不表2中存在table1的
像
圖片
id type name
502 1 summer.gif
SEOImages
id idimage ... ...
1000 501 ... ...
現在我想選擇Images
表中的所有行,其id與不匹配idimage SEOImages
表,並將這些行插入到SEOImages
表中。
選擇行和表2中插入它從一個表中選擇行並插入到其他表的不表2中存在table1的
像
圖片
id type name
502 1 summer.gif
SEOImages
id idimage ... ...
1000 501 ... ...
現在我想選擇Images
表中的所有行,其id與不匹配idimage SEOImages
表,並將這些行插入到SEOImages
表中。
方法:
Insert into Table2
select A,B,C,....
from Table1
Where Not Exists (select *
from table2
where Your_where_clause)
實施例:
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);
查詢:
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
INSERT INTO SeoImages
(IdImage)
SELECT ID
FROM Images
WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages)
INSERT INTO SEOImages
SELECT *
FROM Images
WHERE NOT EXISTS (SELECT 1
FROM Images t1, SEOImages t2
WHERE t1.id=t2.id) ;
1使用(不)存在,而不是(未)在 – Sam