2016-08-19 45 views
1

比方說,我在SQL Server 2008中,UsersSiteUserSite 3個表:尋找失蹤的連接表的SQL Server記錄

+-------+ +-------+ +-------------+ 
| User | | Site | | User Site | 
+-------+ +-------+ +-------------+ 
| User1 | | Site1 | | User1 Site1 | 
| User2 | | Site2 | | User1 Site2 | 
| User3 | +-------+ | User1 Site3 | 
+-------+     | User2 Site1 | 
          | User2 Site3 | 
          | User3 Site1 | 
          +-------------+ 

期望的結果:對於每個UserSite組合必須有一個記錄在UserSite這樣的:

+-------------+ 
| User Site | 
+-------------+ 
| User1 Site1 | 
| User1 Site2 | 
| User1 Site3 | 
| User2 Site1 | 
|*User2 Site2*| Inserted 
| User2 Site3 | 
| User3 Site1 | 
|*User3 Site2*| Inserted 
|*User3 Site3*| Inserted 
+-------------+ 

我只能插入新記錄,並且不能從頭改寫表。

有沒有辦法與SQL Server做到這一點?

回答

4

我可能會提出一個強力方法。截斷表,然後插入所有的值:

truncate table UserSite; 

insert into UserSite(User, Site) 
    select u.user, s.site 
    from users u cross join sites s; 

你可以只用一個稍微複雜的查詢添加新的:

insert into UserSite(User, Site) 
    select u.user, s.site 
    from users u cross join 
     sites s 
    where not exists (select 1 
         from usersite us 
         where us.user = u.user and us.site = s.site 
        ); 
+1

我不能截斷表。第二個查詢可能會起作用,我現在試試吧 – Szer

+0

像魅力一樣工作。謝謝! – Szer

+0

@Gordon爲什麼你的第二個查詢比用戶站點表字段爲空的「用戶站點」表的左外連接更可取? –

1

使用CROSS JOIN

SELECT 
* 
FROM Users 
CROSS JOIN Site 
1

如果你只想選擇缺失的記錄,試試這個:

SELECT * 
FROM Users 
CROSS JOIN Site 

EXCEPT 

SELECT * 
FROM UserSite