Link to home
Start Free TrialLog in
Avatar of qz8dsw
qz8dswFlag for New Zealand

asked on

Inner, outer, left and right join question

Hi all,
Joins have always confused the heck out of me and how to best use them (Or even use them sometimes)

Consider 2 tables like this in the same database

Table1                        Table2
SharedKey                  SharedKey
blah1                          Blah4
blah2
blah3
MyDate

SharedKey is a numeric
All the blahs are strings
MyDate is a date

As we can see it has a shared key. Great, the 2 tables can be searched across giving us merged results between the 2 tables.
Now a client wants merged results from both tables where MyDate from table1 is > 1/1/2000 and < 1/1/2001 and where Blah4 from table2 = "fred"
This from what I can see would be a great use of a join.
So from what I can see we would do a select * from Table1 where mydate > '1/1/2000' and mydate < '1/1/2001' as first_table
and do a select * from Table2 where Blah4 = "fred" as second_table,
then join the results where first_table.SharedKey = second_table.SharedKey

Now just so you know, I'll need abit of help understanding the join so that way I'll not need to keep on scratching my head over them all the time.

Thanks in advance,
Terry
ASKER CERTIFIED SOLUTION
Avatar of TextReport
TextReport
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The example below will include all records from table1 and only the FRED's from table 2
Cheers, Andrew
SELECT t1.SharedKey
     , t1.blah1
     , t1.blah2
     , t1.blah3
     , t2.Blah4
     , t1.MyDate
FROM table1 T1
   LEFT OUTER JOIN (SELECT * 
                    FROM table2
                    WHERE Blah4 = 'fred'
                   ) T2
   ON T1.SharedKey = t2.SharedKey
WHERE t1.MyDate > '20000101' 
AND   t1.MyDate < '20010101'

Open in new window

Avatar of qz8dsw

ASKER

Wow,
Between the explaination and the queries you have both finally cleared this up for me.
Old standard of it seems so simple now you understand it. Seeing the results of Andrews queries coupled with the explainations got this one done. (I'm a lets see if this works person, does it show. LOL!)

Thanks alot appari and Andrew for clearing this one up for me.
Terry