Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unmatched records with SQL

Tags:

sql

select

I'm trying write a query to find records which don't have a matching record in another table.

For example, I have a two tables whose structures looks something like this:

Table1
    State | Product | Distributor | other fields
    CA    | P1      |  A          | xxxx
    OR    | P1      |  A          | xxxx
    OR    | P1      |  B          | xxxx
    OR    | P1      |  X          | xxxx
    WA    | P1      |  X          | xxxx
    VA    | P2      |  A          | xxxx

Table2
    State | Product | Version | other fields
    CA    | P1      |  1.0    | xxxx
    OR    | P1      |  1.5    | xxxx
    WA    | P1      |  1.0    | xxxx
    VA    | P2      |  1.2    | xxxx

(State/Product/Distributor together form the key for Table1. State/Product is the key for Table2)

I want to find all the State/Product/Version combinations which are Not using distributor X. (So the result in this example is CA-P1-1.0, and VA-P2-1.2.)

Any suggestions on a query to do this?

like image 873
J.T. Grimes Avatar asked Feb 03 '09 19:02

J.T. Grimes


People also ask

How do I find unmatched rows in SQL?

LEFT JOIN returns only unmatched rows from the left table, as well as matched rows in both tables. RIGHT JOIN returns only unmatched rows from the right table , as well as matched rows in both tables. FULL OUTER JOIN returns unmatched rows from both tables,as well as matched rows in both tables.

WHERE can I find mismatch records in SQL?

Select Id_pk, col1, col2...,coln from table1 MINUS Select Id_pk, col1, col2...,coln from table2; You can quickly check how many records are having mismatch between two tables. The only drawback with using UNION and MINUS is that the tables must have the same number of columns and the data types must match.


2 Answers

SELECT
    *
FROM
    Table2 T2
WHERE
    NOT EXISTS (SELECT *
        FROM
           Table1 T1
        WHERE
           T1.State = T2.State AND
           T1.Product = T2.Product AND
           T1.Distributor = 'X')

This should be ANSI compliant.

like image 55
gbn Avatar answered Oct 31 '22 02:10

gbn


In T-SQL:

SELECT DISTINCT Table2.State, Table2.Product, Table2.Version
FROM Table2 
  LEFT JOIN Table1 ON Table1.State = Table2.State AND Table1.Product = Table2.Product AND Table1.Distributor = 'X'
WHERE Table1.Distributor IS NULL

No subqueries required.

Edit: As the comments indicate, the DISTINCT is not necessary. Thanks!

like image 27
mwigdahl Avatar answered Oct 31 '22 03:10

mwigdahl