Re: SQL question!
| From: | Michael Forbes | Date: | Tue, 04 May 2004 02:19:06 +0000 |
| Subject: | Re: SQL question! | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-34262@lists.php.net to get a copy of this message | ||
What you wrote will give you the list of users who also happen to have comments. What you really want is more like this:
SELECT Users.ID, Users.UserName, Comments.Description
FROM Users LEFT JOIN Comments
ON Users.ID = Comments.UserID;
(note that you'll need to have the UserID foreign key in your Comments table. Also, the "LEFT JOIN" phrase tells whatever sql back-end you're using that you want -all- records from the users table, regardless of whether or not they have a comment-- and any comments per user in the comments table. If you want to eliminate users who don't have comments, use an INNER JOIN instead.
-Mike Forbes
Bruno Braga wrote:
Hey. I have these tables. Users ( id,name,etc ) Coments : ( id , comment ) How do I do this kind of query: I thought in one thing like this but I cant figure it out. Example: Select * from users order by id desc in (select count (id) from comments) Expected result: List of users: * User1 See comments ( 32 comment in database ) * User2 See coments (13 comments in database ) * etc. thanks in advanced. Bruno