2012-08-01 32 views
1

我在使用此查询获取有关不同表中的回复数的论坛主题排序时遇到问题。我在左边连接之前尝试了这种方式,但在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 

它给了我这是一个错误:

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 

这是在之前的工作中查询:

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

为了呼应我使用:

$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)){ 

当回声时,我只得到1个左边的结果ñ但与旧的我得到了2,这是我的预期。

+1

你不应该在新应用程序中使用mysql_query,因为它太危险了。改用PDO或'mysqli'。请使用[正确的SQL转义](http://bobby-tables.com/php)。 – tadman 2012-08-01 16:39:02

回答

6

这是因为子句的顺序是错误的。

这是正确的语法(每评论EDITED下面):

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 

当你执行任何类型的JOIN,为您营造一种“虚表”的是所有表中涉及的合并。 Where子句在这个“虚拟表”上运行,所以如果你仔细想一想,在创建这个表之后WHERE子句才有意义。

+0

阅读我的文章,请我已经尝试过,但它只提取一些数据 – kezi 2012-08-01 16:15:36

+2

然后你的查询是不正确的。让你的语法无效不会改变任何东西。 – 2012-08-01 16:16:10

+0

也许你想要一个'OUTER JOIN'? – paddy 2012-08-01 16:16:52