Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join two tables but only return rows that don't match?

I have two tables which look like this:

T1:  ID  |  Date  |  Hour  | Interval T2:  ID  |  Date  |  Hour 

I basically need to join these tables when their IDs, dates, and hours match. However, I only want to return the results from table 1 that do not match up with the results in table 2.

I know this seems simple, but where I'm stuck is the fact that there are multiple rows in table 1 that match up with table 2 (there are multiple intervals for any given hour). I need to return all of these intervals so long as they do not fall within the same hour period in table 2.

Example data:

T1:  1  |  1/1/2011  |  1  |  1      1  |  1/1/2011  |  1  |  2      1  |  1/1/2011  |  2  |  1      1  |  1/1/2011  |  2  |  2  T2:  1  |  1/1/2011  |  1 

My expected result set for this would be the last two rows from T1. Can anyone point me on the right track?

like image 480
Breakthrough Avatar asked Jul 07 '11 16:07

Breakthrough


People also ask

Which join returns rows that do not have matching values?

The outer join is needed when you wish to include rows that do not have matching values.

How do you select rows with no matching entry in another table?

1 Answer. Here, LEFT JOIN is used to return all the rows from TableA even though they don't match with the rows in TableB. You can observe that WHERE tb.ID IS NULL clause; there will be no records in TableB for the particular ID from TableA.

How do you join two tables that are not related?

The most common way to join two unrelated tables is by using CROSS join, which produces a cartesian product of two tables. For example, if one table has 100 rows and another table has 200 rows then the result of the cross join will contain 100x200 or 20000 rows.

Can we apply joins on 2 tables which has no related data?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL.


2 Answers

SELECT T1.*     FROM T1     WHERE NOT EXISTS(SELECT NULL                          FROM T2                          WHERE T1.ID = T2.ID                               AND T1.Date = T2.Date                              AND T1.Hour = T2.Hour) 

It could also be done with a LEFT JOIN:

SELECT T1.*     FROM T1         LEFT JOIN T2             ON T1.ID = T2.ID                 AND T1.Date = T2.Date                 AND T1.Hour = T2.Hour     WHERE T2.ID IS NULL 
like image 132
Joe Stefanelli Avatar answered Oct 26 '22 03:10

Joe Stefanelli


Use a LEFT JOIN and filter out the lines that have non-NULL T2 columns:

SELECT T1.* FROM T1 LEFT JOIN T2 ON T1.ID = T2.ID     AND T1.Date = T2.Date AND T1.Hour = T2.Hour     WHERE T2.ID IS NULL 
like image 30
Costi Ciudatu Avatar answered Oct 26 '22 04:10

Costi Ciudatu