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;
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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With