I have a table (orders) with order id, location 1, location 2 and another table (mileage) with location 1 and location 2.
I'm using the Except action to return those location pairs in orders that are not in mileage. But I'm not sure how I can also return the corresponding order_id that belongs to those pairs (order_id doesn't exist in the mileage table). The only thing I can think of is having an outer select statement that searches orders for those location pairs. I haven't tried it but I'm looking for other options.
I have something like this.
SELECT location_id1, location_id2
FROM orders
except
SELECT lm.origin_id, lm.dest_id
from mileage
How can I also retrieve the order id for those pairs?
How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
SQL NOT EXISTS in a subquery In simple words, the subquery with NOT EXISTS checks every row from the outer query, returns TRUE or FALSE, and then sends the value to the outer query to use. In even simpler words, when you use SQL NOT EXISTS, the query returns all the rows that don't satisfy the EXISTS condition.
You can use CTE. Find sum of code as it is integer. If it is greater than 1, it means somewhere for this value there is 2.
Outer joins return all rows from one table and matching rows from the second table.
You might try using a Not Exists statement instead:
Select O.order_id, O.location_id1, O.location_id2
From orders As O
Where Not Exists (
Select 1
From mileage As M1
Where M1.origin_id = O.location_id1
And M1.dest_id = O.location_id2
)
Another solution if you really wanted to use Except
Select O.order_id, O.location_id1, O.location_id2
From Orders As O
Except
Select O.order_id, O.location_id1, O.location_id2
From Orders As O
Join Mileage As M
On M.origin_id = O.location_id1
And M.dest_id = O.location_id2
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