Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding pairs that do not exist in a different table

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?

like image 258
Gabe Avatar asked Mar 28 '11 19:03

Gabe


People also ask

How can I get data that is not present in another table?

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.

How do you check not exists in SQL?

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.

How do you find a pair in SQL?

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.

Which SQL command returns all records from one table and only matched records from a second table?

Outer joins return all rows from one table and matching rows from the second table.


1 Answers

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
like image 131
Thomas Avatar answered Sep 18 '22 13:09

Thomas