Re: Problem with JOIN
| From: | Benjamin Walling | Date: | Thu, 23 May 2002 14:14:21 +0000 |
| Subject: | Re: Problem with JOIN | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-19383@lists.php.net to get a copy of this message | ||
I'm not sure I'm reading what you want correctly, but it sounds like you
really want an INNER JOIN instead of a LEFT JOIN. INNER JOIN will only join
if the records in both tables exist and match on the join criteria. Also,
why are you joining the user_websites table to itself? Just use WHERE
user_websites.user_id = '3'. Generally, you would join the other tables
based on fields in the main table, instead of on constants.
SELECT
w.website,
c.comment,
i.icq,
s.signature
FROM user_websites w
INNER JOIN user_comments c ON w.user_id = c.user_id
INNER JOIN user_icq i ON w.user_id = i.user_id
INNER JOIN user_signature s ON w.user_id = s.user_id
WHERE w.user_id = '3'
This will only return records that exist in all of the tables. If there are
any records that are not essential, change them to a LEFT JOIN. For
example, if you icq and signature were optional return values, you would
LEFT JOIN them instead of INNER JOIN, then only records that matched in
user_websites and user_comments would be returned, and they would include
anything that was found in user_icq or user_signature.
"Andy" <news.letters@gmx.de> wrote in message
news:20020523131903.3003.qmail@pb1.pair.com...
> Hi there,
>
> I do want to pull out some data of a user. I did normalize the tables, so
> there is a table for website, comment ...
>
> Now I would like to pull out the users website, comment.. but only if
there
> is one.
>
> Unfortunatelly my select stmt returns all 50000 records of the website
> table:
>
> SELECT
> w.website,
> c.comment,
> i.icq,
> s.signature
> FROM
> user_websites
> LEFT JOIN user_comments AS c ON c.user_id = '3'
> LEFT JOIN user_icq AS i ON i.user_id = '3'
> LEFT JOIN user_signature AS s ON s.user_id = '3'
> LEFT JOIN user_websites AS w ON w.user_id = '3'
>
> Somehow my syntax must be wrong, but I can not find the error :-(
>
> Maybe one of you guys does know why.
>
> Thanx in advance,
>
> Andy
>
>