0

I have two tables:

Transactions:
+---------+--------------+------------+-----------+
| id      | address_from | address_to | value     |
+---------+--------------+------------+-----------+
| 1       |        1     |     2      | 1000      |
| 2       |        1     |     2      | 500       |
+---------+--------------+------------+-----------+
Addresses:
+---------+--------------+
| id      | address      |
+---------+--------------+
| 1       |   address1   |
| 2       |   address2   |
+---------+--------------+

I need to get all transactions with adresses instead id:

SELECT * FROM transactions tr
JOIN addresses ad ON tr.address_from = ad.id OR tr.address_to = ad.id
WHERE tr.address_from = 1 OR tr.address_to = 1

And then i get following result:

+---------+--------------+-----------+
| id      | address      | value     |
+---------+--------------+-----------+
| 1       |  address1    |   1000    |
| 1       |  address1    |   1000    | 
| 2       |  address2    |   500     |
| 2       |  address2    |   500     |
+---------+--------------+-----------+

But i need something like this:

+---------+--------------+-------------+-----------+
| id      | address_from | address_to  | value     |
+---------+--------------+-------------+-----------+
| 1       |   address1   |   address2  | 1000      |
| 2       |   address1   |   address2  | 500       |
+---------+--------------+-------------+-----------+

How can I get that result?
And isn't it so expensive to do join on two columns?

1 Answer 1

3

You could try with 2 join on same table to get the expected result

SELECT tr.id,adf.address as address_from,adt.address as address_to,tr.value
    FROM transactions tr
JOIN addresses adf ON tr.address_from = adf.id
JOIN addresses adt ON tr.address_to = adt.id
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I didn't even think about this possibility. But how will a lot of joins affect a table with millions of records?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.