SQL Server中的关联表

时间:2016-04-14 05:49:23

标签: sql-server

如果我有4张桌子(陆军,海军,空军,海军陆战队),所有人都有序列号作为主键和名字。我有一个表操作,其中op_num作为主键和op_name。我还有一个表操作成员,它将操作表与其他4个表相关联,如何编写单个SQL语句,返回隐蔽操作的成员名称(无论服务分支如何)沙漠风暴& #39;使用Microsoft SQL语法?

我有这个

SELECT Soldier.Name FROM Operation_Member
INNER JOIN Operation
    ON Operation.op_num = Operation_Member.op_num
INNER JOIN
(
    SELECT ser_num, name FROM Army
    UNION ALL
    SELECT ser_num, name FROM Navy
    UNION ALL
    SELECT ser_num, name FROM Air_Force
    UNION ALL
    SELECT ser_num, name FROM Marines
) Soldier
    ON Soldier.ser_num = Operation_Member.ser_num
WHERE Operation.op_name = 'Desert Storm'

但如果序列号在所有四个服务表中都不是唯一的,那么这不会起作用。 有没有办法确保它适用于那种情况?

1 个答案:

答案 0 :(得分:1)

如果序列号在所有四个服务表中都不是唯一的,则无法知道在Operation_Member中引用了哪些重复项,除非您也将服务分支存储在Operation_Member中。

如果您这样做,则查询将成为此

SELECT Soldier.Name 
FROM 
    Operation
    INNER JOIN 
    Operation_Member ON Operation.op_num = Operation_Member.op_num
    INNER JOIN
    (
        SELECT branchid, ser_num, name FROM Army
        UNION ALL
        SELECT branchid, ser_num, name FROM Navy
        UNION ALL
        SELECT branchid, ser_num, name FROM Air_Force
        UNION ALL
        SELECT branchid, ser_num, name FROM Marines
    ) Soldier
        ON Soldier.ser_num = Operation_Member.ser_num
                 AND Soldier.branchid= Operation_Member.branchid
WHERE Operation.op_name = 'Desert Storm'

如果你不这样做,就无法消除歧义