2

I have two tables:

Table Users

UserId     Name
1          John
2          Alice
3          Tom
4          Charles

and

Table Clients

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

I would like to make a SQL query where for

Clients.Id = 1

the results are like:


Id         Name1          Name2       Name3
1          John            Tom       Charles

Using INNER JOIN I am able to do that for each column from Clients but not for the whole record (all three columns).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mugur Ungureanu
  • 161
  • 1
  • 11

3 Answers3

5

You need to join table users thrice on 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 Demo

John Woo
  • 258,903
  • 69
  • 498
  • 492
1

You need to join to the Users table once for each name. Given you have 3 columns, it is likely one or more may be nullable, so you're more likely to want LEFT JOINs than INNER JOINs.

   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
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
1

There is one more option which doesn't require excessive join

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
Aleksandr Fedorenko
  • 16,594
  • 6
  • 37
  • 44