Reputation: 181
I am trying to join two tables Table1 and Table2 using the query below. I want all the columns (and rows) from Table1 and Column 'BasedOnDate' from Table2. The problem is, all the values in column 'BasedOnDate' are being set to 1 after the left join, instead of on the rows where is a match in both the tables (likes row 1 in Table1 and Row 1 in Table2. Can someone comment on where the problem lies?
The query I am using right now:
SELECT Table1.*, Table2.BasedOnDate
FROM Table1 LEFT JOIN Table2 ON (Table1.Name = Table2.Name) AND
(Table1.[Date-4] = Table2.[Date-4]) AND
(Table1.[Date-3] = Table2.[Date-3]) AND
(Table1.[Date-2]= Table2.[Date-2]) AND
(Table1.[Date-1] = Table2.[Date-1]) AND
(Table1.ID = Table2.ID) AND
(Table1.Site = Table2.Site);
Table2:
Site ID Date-1 Date-2 Date-3 Date-4 Name BasedOnDate
00001 201 3/30/2011 4/6/2011 4/3/2011 4/6/2011 Name-1 1
Table1:
Site ID Date-1 Date-2 Date-3 Date-4 Name
00001 201 3/30/2011 4/6/2011 4/3/2011 4/6/2011 Name-1
00001 101 5/21/2011 5/28/2011 5/21/2011 5/28/2011 Name-2
Upvotes: 1
Views: 166
Reputation: 3252
As I recreated your situation I can confirm that using correct syntax the query works: retreives all column of Table1
plus the joined Table2
's BasedOnDate
. Where there's no match the query returns null
for BasedOnDate
.
SITE ID DATE1 DATE2 DATE3 DATE4 NAME BASEDONDATE
1 201 March, 30 2011 April, 06 2011 April, 03 2011 April, 06 2011 Name-1 1
1 101 May, 21 2011 May, 28 2011 May, 21 2011 May, 28 2011 Name-2 (null)
You can check here: http://sqlfiddle.com/#!6/a56ee/2
If you need further research pls take a comment. Hope it helps you!
Upvotes: 1