我有两张桌子:
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我可以为客户端的每一列执行此操作,但不能为整个记录(所有三列)执行此操作。
答案 0 :(得分:5)
您需要在表users
上连接表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
答案 1 :(得分:1)
您需要为每个名称加入一次Users表。鉴于你有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
答案 2 :(得分: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