简体   繁体   中英

SQL join different tables depending on row information

Suppose I have table A with a field that can be either 1 or 2...

How do I select such that for each row in table A, if the field is 1, join the select with table B and if the field is 2, join the select with table C?

(
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
)

Somethine like this can work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM