SQL根据行信息连接不同的表

时间:2010-03-13 23:17:56

标签: sql select join

假设我的表A的字段可以是1或2 ......

如何选择表A中的每一行,如果字段为1,则将select与表B连接,如果字段为2,则将select与表C连接?

2 个答案:

答案 0 :(得分:8)

(
SELECT MyField1, MyField2 FROM A
INNER JOIN B ON A.Id = B.Id
AND A.MyField = 1
)
UNION
(
SELECT MyField1, MyField2 FROM A
INNER JOIN C ON A.Id = C.Id
AND A.MyField = 2
)

答案 1 :(得分:0)

这样的东西可以起作用

DECLARE @TableA TABLE(
        ID INT
)

DECLARE @TableB TABLE(
        ID INT,
        Val VARCHAR(50)
)

DECLARE @TableC TABLE(
        ID INT,
        Val VARCHAR(50)
)

INSERT INTO @TableA SELECT 1
INSERT INTO @TableA SELECT 2

INSERT INTO @TableB SELECT 1, 'B'

INSERT INTO @TableC SELECT 2, 'C'

SELECT  *
FROM    @TableA a INNER JOIN
        @TableB b   ON  a.ID = b.ID
                    AND a.ID = 1
UNION 
SELECT  *
FROM    @TableA a INNER JOIN
        @TableC c   ON  a.ID = c.ID
                    AND a.ID = 2