Reply to Re: Querying joined tables with 0 results

Your name:

Reply:


Posted by Hugo Kornelis on 01/18/06 22:47

On 18 Jan 2006 11:44:39 -0800, commanderjason@gmail.com wrote:

(snip)
>select max(username), count(answer) from tblUsers
>left outer join tblanswers on tblAnswers.userid = tblUSers.id
>where tblAnswers.answer = 4
>group by tblUsers.id

Hi commanderjason,

The outer join ensures that rows from tblUsers are retained even when
there's no match in tblAnswers. But this only applies to the ON
condition. If for a row from tblUsers, no row in tblAnswers satisfies
that condition (ie tblAnswers.userid = tblUsers.userid), then it will be
retained with NULL values for the columns from the tblAnswers table.

After that, the WHERE condition will throw away all rows produced by the
join that have tblAnswer other than 4 - including the ones with
tblAnswer set to NULL as a result of the outer join. Effectively, you
have negated the effect of the outer join and turned it back into an
inner join.

So far the theory. The answer is much easier: move the WHERE condition
to the ON clause.

select max(username), count(answer) from tblUsers
left outer join tblAnswers on tblAnswers.userid = tblUsers.userid
and tblAnswers.answer = 4
group by tblUsers.userid

(Note that I only had to change "where" to "and" here!)

--
Hugo Kornelis, SQL Server MVP

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация