2

我有两张桌子:

Table Users

UserId     Name
1          John
2          Alice
3          Tom
4          Charles

Table Clients

Id         Name1          Name2      Name3
1            1              3          4
2            2              1          3

我想在哪里进行 SQL 查询

Clients.Id = 1

结果如下:


Id         Name1          Name2       Name3
1          John            Tom       Charles

使用 INNER JOIN 我可以对来自客户的每一列执行此操作,但不能对整个记录(所有三列)执行此操作。

4

3 回答 3

5

您需要在 tableusers上三次加入 table client

SELECT  a.ID,
        b.name name1,
        c.name name2,
        d.name name3
FROM    clients a
        INNER JOIN users b
            ON a.name1 = b.userID
        INNER JOIN users c
            ON a.name2 = c.userID
        INNER JOIN users d
            ON a.name3 = d.userID
WHERE   a.ID = 1

SQLFiddle 演示

于 2012-10-02T09:16:22.753 回答
1

还有一种不需要过多连接的选项

SELECT c.Id, MAX(CASE WHEN u.UserID = c.Name1 THEN u.Name END) AS Name1,
             MAX(CASE WHEN u.UserID = c.Name2 THEN u.Name END) AS Name2,
             MAX(CASE WHEN u.UserID = c.Name3 THEN u.Name END) AS Name3
FROM dbo.Users u JOIN dbo.Clients c ON u.UserId IN (c.Name1, c.Name2, c.Name3)
WHERE c.Id = 1
GROUP BY c.Id
于 2012-10-02T12:08:10.670 回答
1

您需要为每个名称加入用户表一次。鉴于您有 3 列,很可能有一列或多列可以为空,因此您更可能需要 LEFT JOIN 而非 INNER JOIN。

   select c.id, u1.name name1, u2.name name2, u3.name name3
     from Clients c
left join Users u1 on u1.UserId = c.name1
left join Users u2 on u2.UserId = c.name2
left join Users u3 on u3.UserId = c.name3
    where c.Id = 1
于 2012-10-02T09:23:07.890 回答