简体   繁体   English

在子句后左联接

[英]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. 我在where之前使用Left join尝试了此操作,但在while循环中遗漏了一些数据。

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. 回显时,左连接仅得到1个结果,而旧连接则得到2个,这是我所期望的。

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. 当您执行任何一种JOIN ,您将创建一种“虚拟表”,该表是所涉及的所有表的合并。 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. where子句在此“虚拟表”上运行,因此,如果考虑一下,仅在创建该表之后使用WHERE子句才有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM