Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left Join After Where Clause

I'm having trouble with this query that fetches sorts forum topics on the number of replies in a different table. I tried this with Left join before the where but some data was left out in my while loop.

SELECT forum_topics.*, COUNT(forum_posts.comment_id) AS replies 
FROM forum_topics 
WHERE forum_topics.subcat_id = '$subcatid' 
LEFT JOIN forum_posts 
ON forum_topics.topic_id=forum_posts.topic_num  
ORDER BY replies DESC

It gives me this as an error:

You have an error in your SQL syntax; check the manual that corresponds to your 
MySQL server version for the right syntax to use near 'LEFT JOIN forum_posts ON 
forum_topics.topic_id=forum_posts.topic_num ORDER BY r' at line 1

This is the query that was working before:

SELECT * FROM forum_topics WHERE subcat_id = '$subcatid' ORDER BY date DESC

To echo I use:

$getChildCategory = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($get); 
if($num == 0){ echo 'No Posts';}
else{
    while ($row = mysql_fetch_assoc($get)){

When echoing I only get 1 result with the left join but with the old one I got 2 which is what I expected.

like image 457
keji Avatar asked Oct 22 '25 12:10

keji


1 Answers

That's because the clauses are in the wrong order.

This is the correct syntax (EDITED per comments below):

SELECT `forum_topics`.*, COUNT(`forum_posts`.`comment_id`) AS `replies`
FROM `forum_topics`
LEFT JOIN `forum_posts` 
ON `forum_topics`.`topic_id` = `forum_posts`.`topic_num`
WHERE `forum_topics`.`subcat_id` = '$subcatid'
GROUP BY `forum_posts`.`topic_num`
ORDER BY `replies` DESC

When you perform any sort of JOIN, you create a sort of "virtual table" that is an amalgamation of all tables involved. The where clause operates on this "virtual table", so if you think about it it only makes sense for the WHERE clause to go after this table has been created.

like image 153
DaveRandom Avatar answered Oct 24 '25 03:10

DaveRandom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!