在Where Where Clause之后加入

kej*_*eji 1 php mysql 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
Run Code Online (Sandbox Code Playgroud)

它给我这个错误:

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
Run Code Online (Sandbox Code Playgroud)

这是之前正在运行的查询:

SELECT * FROM forum_topics WHERE subcat_id = '$subcatid' ORDER BY date DESC
Run Code Online (Sandbox Code Playgroud)

为了回应我使用:

$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)){
Run Code Online (Sandbox Code Playgroud)

回音时,我只得到左连接的1个结果,但是旧的得到2,这是我的预期.

Dav*_*dom 6

那是因为条款的顺序错误.

这是正确的语法(以下评论编辑):

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
Run Code Online (Sandbox Code Playgroud)

当您执行任何类型的操作时JOIN,您将创建一种"虚拟表",它是所有相关表的合并.where子句在这个"虚拟表"上运行,所以如果你考虑它,只有WHERE在创建了这个表之后才能使用该子句.

  • 那你的查询是不正确的.使语法无效不会改变任何东西. (2认同)
  • @Matt如果可以,那不是很棒吗?也许我可以把每个应用程序都写成`read my mind(){除非你知道更好()}`它会像魔法一样工作. (2认同)