I am improving my php script which has two simple sql queries. What Im trying to do is to combine the two queries into one.
1st query:
SELECT categories.*, entries.*
FROM categories, entries
WHERE entries.cat_id = categories.cat_id
ORDER BY dateposted ASC
LIMIT 5;
2nd query:
SELECT comments.*
FROM comments
WHERE comments.entry_id = '. $row['id'].';
These two work great when separate. I just need to combine them into one(still simple, no UNION or INNER JOINs please) and possibly count a number of comments for a particular entry right in the query.
Also, my “comments” table has five columns (comment_id, post_id, author, body, dateposted) if this is any helpful to know.
I tried different ways. Something like this:
SELECT categories.*, entries.*, COUNT(comments.entry_id) AS comm_num
FROM categories, entries, comments
WHERE entries.cat_id = categories.cat_id
AND comments.entry_id = entries.id
ORDER BY dateposted ASC LIMIT 5;
did not work…
Any help will be greatly appreciated.
Your first query is essentially a join, and it may not be any faster. You can query for entries (while displaying the corresponding category information) like so:
Also, it sounds like you don’t actually want to return each comment row in this query, but rather just obtain a comment count per “entry”. For that count, you can likely do this:
Note the COUNT function is counting comment IDs, not entry IDs.