mySQL returning multiple rows from other tables

nry

Limp Gawd
Joined
Jul 10, 2008
Messages
409
I am fairly clued up with mySQL and can do joins, sub queries at a basic level but I have never had to return data in such a fashion before.

What I need to return on a basic level (re-nammed to a more common use as I don't have a DB structure to post online) is return all users with all their posted blog articles in one query.

I figure the most logical way to do this would be to return all users in order by their ID with a join on the blog so I would get an array back like follows:

USERID, NAME, BLOGTITLE, BLOGCONTENT
1, Bob, some crazy title, this is how not to write SQL :p
1, Bob, my first post, oh hello
2, Jack, hello, hi hardforum
2, Jack, example, bored now

Guess the query would be along the lines of
SELECT * FROM users
LEFT JOIN articles
ON users.userid = articles.userid
ORDERBY users.userid

So I am returning identical data, eg USERID, NAME multiple times. I can then group these in PHP and create an associative based on users with all their articles as a variable in that array, say ARTICLES

Is this the correct way of doing it?
Is a left join the correct one to use?
Are there any alternatives?

Sorry if I haven't explained this very well, been a long week!
 
Is this the correct way of doing it?
Is a left join the correct one to use?
Are there any alternatives?
A LEFT JOIN would be appropriate if you were deleting the user row on the table (versus updating an "IsDeleted" column and filtering them out in a query). So if an article record cannot exist without a matching user record, then do an INNER JOIN instead.

Depending on your display needs, you may want to extend the ORDER BY statement to also factor the date/time that the article was created:
Code:
ORDER BY users.userid ASC, article.createdon DESC
 
Back
Top