I’ve never used MySQL for anything involving many tables; when I have, I’ve nested queries to get the information that I need.
A good example I can think of when I want to output some blog posts and their related comments.
The tables could look like this (simplified to keep the question short):
posts:
id | title | content
comments:id | post_id | author | content
Where comments.post_id is obviously linked to the relevant post.id.
I’d then output the posts and the comments like this (I’d normally expand the query a little more, but again want to keep the question short):
// Get posts.
$posts = mysql_query("SELECT * FROM posts ORDER BY id DESC");
while($prow = mysql_fetch_assoc($posts))
{
$pid = $prow["id"];
// Write post.
echo '
<h2 id="post' . $pid . '">' . $prow["title"] . '</h2>
<p>' . $prow["content"] . '</p>';
// Get related comments.
$cquery = mysql_query("SELECT * FROM comments WHERE post_id = '$pid' ORDER BY id DESC");
while($crow = mysql_fetch_assoc($cquery))
{
$cid = $crow["id"];
// Write comment.
echo '<p id="comment' . $cid . '"><strong>' . $crow["author"] . ':</strong> ' . $crow["content"] . '</p>';
}
}
As far as I can tell, this would mean that if I had 10 blog posts, there would be 11 queries (1 for the posts and then an additional query for the comments for each post). That doesn’t seem sane.
I’m sure there’s a way to create a query that will select the posts as well as the relevant comments all-in-one, I just have no idea what the correct way to do that is. I’ve vaguely heard about joins, but when I read about them, they aren’t making much sense to me.
It would be nice to end up with something roughly like:
$query = mysql_query("
SELECT
posts.id,
posts.title,
posts.content,
comments.id,
comments.author,
comments.content
FROM
posts,
comments
WHERE
comments.post_id = post.id,
");
And then I could just do something like this:
while($row = mysql_fetch_assoc($query))
{
echo '
<h2 id="post' . $row["posts.id"] . '">' . $row["posts.title"] . '</h2>
<p>' . $row["posts.content"] . '</p>';
// Somehow iterate over the comments and display them.
//
}
I hope I explained what I want to achieve properly.
I think your way would work (at least it would in MS SQL), but the standard way would be to use a join: