Help - Search - Members - Calendar
Full Version: SQL question
bargainshare.com > Community > Computer & Tech Help
qwex
sql experts, I've got a question...

say I have Table1(id, date, n)
and Table2(id, n, value)

I want to return all records with a given id, where Table1.n = Table2.n, and there may or may not be a Table2 record for every (id, n) pair.

I tried:

SELECT * FROM Table1 LEFT JOIN Table2 ON Table1.n=Table2.n WHERE Table1.id=Table2.id AND Table1.id=##

but it's only returning records which have an (id, n) pair in Table2. I want everything in Table1, whether or not the given id and n-value appear in Table2...

I also tried changing it to ON Table1.id=Table2.id, but that returns everything from Table1 once for every record in Table2.

am I doing something wrong here?
BlueTDimly
LEFT OUTER JOIN is what you want (or whatever the syntax is in your dialect)
qwex
QUOTE(BlueTDimly @ 8-22-06, 1:08pm) *
LEFT OUTER JOIN is what you want (or whatever the syntax is in your dialect)


tried that too, but the same results.

e.g. I have:

CODE
Table1
------
id  date  n
31  blah  1
31  blah  2
31  blah  3
31  blah  4

Table2
------
id  n  value
31  1  3200
31  2  4010


so I want every record in Table1, with an added field "value" in the output with the records in Table2 that match up. so I want a query to produce:

CODE
id  date  n  value
31  blah  1  3200
31  blah  2  4010
31  blah  3  null
31  blah  4  null


am I correct in joining on Table1.n=Table2.n?
NARC
Since you are joining on both ID AND n, you have to outer join both of them.
Here's what Access SQL says:

SELECT Table1.id, Table1.date, Table1.n, Table2.value
FROM Table1 LEFT JOIN Table2 ON (Table1.n = Table2.n) AND (Table1.id = Table2.id);
CODE
id      date       n  value
1       08/01/2006 a  500
2       08/02/2006 b  600
3       08/03/2006 c
qwex
thanks guys, looks like both of you were right, and I had the mistake - I had a WHERE Table1.id=Table2.id clause. when I took that out, I got the results I wanted. dance.gif
garsh
Is this what you want?
CODE
dell=# SELECT * FROm table1;
id | date | n
----+------+---
31 | blah | 1
31 | blah | 2
31 | blah | 3
31 | blah | 4
(4 rows)

dell=# SELECT * FROM table2;
id | n | value
----+---+-------
31 | 1 |  3200
31 | 2 |  4010
(2 rows)

dell=# SELECT t1.id, t1.n, t1.date, t2.value FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.id = t2.id AND t1.n = t2.n;
id | n | date | value
----+---+------+-------
31 | 1 | blah |  3200
31 | 2 | blah |  4010
31 | 3 | blah |
31 | 4 | blah |
(4 rows)


edit: looks like I was late to the party tongue.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.