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?
The outer join is needed when you wish to include rows that do not have matching values.
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.
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.
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.
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
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
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