tags:

views:

27

answers:

2

I have a table T1 with the following columns

T1
----------
ID | Name
----------
1    Sender1
2    Receiver1
3    Receiver2
4    Sender2

Table T2

T1
---------------------
SenderID | ReceiverID
---------------------
1          2
1          3
4          2

I want to join the two tables in such a way that i want to get the sender and the corresponding receiver grouped. I want the names instead of the IDs. How can this be done in one SQL query

Ex:

Sender                Receiver

Sender1       receiver1
              receiver2

Sender2       receiver1
+4  A: 
select a.name Sender, b.name Receiver
FROM t2
INNER JOIN t1 a
ON t2.SenderID = a.ID
INNER JOIN t1 b
ON t2.Receiver = b.ID

Will give you:

SenderID ReceiverID
Sender1 Receiver1
Sender1 Receiver2
Sender2 Receiver1

If you want to group those results on Sender1, and have the receiver names in one column (separated by \n or space or something), use a group by on a.name. In MySQL for example, there is a group_concat for the b.name's.

The query then becomes

select a.name Sender, GROUP_CONCAT(b.name SEPARATOR ' ') Receiver
FROM t2
INNER JOIN t1 a
ON t2.SenderID = a.ID
INNER JOIN t1 b
ON t2.Receiver = b.ID
GROUP BY a.name
Konerak
+1, but the group by Sender is missing.
Stefan Steinegger
+3  A: 

Simply join on T1 twice:

SELECT TS.[Name] AS SenderName, TR.[Name] AS ReceiverName
FROM T2
    INNER JOIN T1 TS ON TS.ID = T2.SenderID
    INNER JOIN T1 TR ON TR.ID = T2.ReceiverID
ORDER BY TS.[Name], TR.[Name]
Chris Latta
+1, but the group by SenderName is missing.
Stefan Steinegger