I'm trying to join a few tables, and have been struggling with this problem for ages. Can anyone help?
There are three tables in question:
There is a many-to-many relationship between ticket and address. (Each ticket can be associated with 0 or more addresses). The requestor table is a junction table between the two. Here's what the tables look like:
table ticket
ticket_id ticket_name
-------------------------
1 One
2 Two
3 Three
table requestor
ticket_id address_id
-------------------------
1 2
2 1
2 3
3 1
3 3
3 4
table address
address_id address
-------------------------
1 a@example.com
2 b@example.com
3 c@example.com
4 d@example.com
Here is the result I'm trying to get. Note that if there are more than one addresses associated with the ticket I only care about the first one.
desired result
ticket_id address
1 b@example.com
2 a@example.com
3 a@example.com
Here's what I'm doing now:
SELECT ticket.ticket_id,
address.address
FROM ticket
LEFT JOIN requestor ON ticket.ticket_id = requestor.ticket_id
LEFT JOIN address ON requestor.address_id = address.address_id
But here is what I'm actually getting:
ticket_id address
1 b@example.com
2 a@example.com
2 c@example.com
3 a@example.com
3 c@example.com
3 d@example.com
Does anyone know how I can restrict the join from joining all the rows from the right-hand column (i.e. requestor) to the ticket? I just want the first match from the requestor table, if there is one.
Thanks,
Antun