SQL Server中的关联表

时间:2016-04-14 04:17:40

标签: sql sql-server

如果我有4个表(Army, Navy, Air Force, Marines),则所有表都有serial number作为主键,name。我有一个operation表,其中op_num为主键,op_name。我还有一个表operation member,它将操作表与其他4个表相关联,如何编写单个SQL语句,返回隐蔽操作“沙漠风暴”的成员名称(无论服务分支如何) '使用Microsoft T-SQL语法?

1 个答案:

答案 0 :(得分:1)

鉴于您的关联表看起来像这样

Operation_Member (op_num, ser_num)

以下查询应返回所需的结果:

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'