在连接表SQL Server

时间:2016-08-19 12:34:33

标签: sql sql-server sql-server-2008 tsql

假设我在SQL Server 2008中有3个表,UsersSiteUserSite

+-------+    +-------+    +-------------+
| 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执行此操作?

3 个答案:

答案 0 :(得分:4)

我可能会建议采用蛮力方法。截断表并插入所有值:

<?php   
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = "pizza";

    $name = "";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    mysql_select_db($dbname);


    $email = "example@gmail.com";
    $query = "Select customer.CustName from customer inner join login on customer.CustID = login.CustID where login.email = '$email'";
    $result = mysql_query($query);
    $num = mysql_num_rows($result);
    while ($row = mysql_fetch_array($result)) {
        $name =  $row["CustName"] ;
    }

    mysql_close($conn);?>

您可以使用稍微复杂的查询添加新的

truncate table UserSite;

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

答案 1 :(得分:1)

使用交叉加入

SELECT 
*
FROM Users
CROSS JOIN Site 

答案 2 :(得分:1)

如果您只想选择缺失的记录,请尝试以下方法:

SELECT *
FROM Users
CROSS JOIN Site 

EXCEPT

SELECT *
FROM UserSite