Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to double JOIN properly in SQL

Tags:

sql

mysql

I'm trying to select all transactions with the billing_address city in 'New York', but with the shipping_address city not in 'New York'. The problem I'm struggling with is that when looking at the transactions table, there's two columns (shipping_address_id and billing_address_id), where the respective id for both is stored in theaddress_table as two seperate records.

Since I need to check whether or not the shipping/billing address is 'New York' for both those columns in the transactions table, I'm trying to do a double join to the address_table in my query, though it doesn't seem to be working properly. Does anyone see where I'm going wrong here? Thanks!

SELECT billing.id AS billing_address, shipping.id AS shipping_address
FROM transactions AS t
LEFT JOIN address_table AS billing
ON t.billing_address_id = billing.id
AND billing.city = 'New York'
AND t.billing_address_id IS NOT NULL
LEFT JOIN address_table AS shipping
ON t.shipping_address_id = shipping.id
AND shipping.city != 'New York'
AND t.shipping_address_id IS NOT NULL;
like image 410
Robby Williams Avatar asked Oct 16 '16 03:10

Robby Williams


People also ask

Can you join twice in SQL?

JOIN is one of the most common statements in SQL. As you may know, it is used to join and combine data from two or more tables into one common data set.

How do I join two joined tables in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

What is the most efficient way of joining 2 table in same database?

Relational algebra is the most common way of writing a query and also the most natural way to do so. The code is clean, easy to troubleshoot, and unsurprisingly, it is also the most efficient way to join two tables.

How can I improve my multiple joins performance?

You should see the Query Execution Plan and optimize the query section by section. The overall optimization process consists of two main steps: Isolate long-running queries. Identify the cause of long-running queries.


1 Answers

Assuming I'm understanding correctly, you just need to use an inner join:

SELECT t.*,
       b.id AS billing_address, 
       s.id AS shipping_address
FROM transactions AS t
       JOIN address_table AS b ON t.billing_address_id = b.id      
       JOIN address_table AS s ON t.shipping_address_id = s.id
WHERE b.city = 'New York' AND
      s.city != 'New York'
like image 96
sgeddes Avatar answered Oct 22 '22 09:10

sgeddes