[英]Left Join After Where Clause
我在使用此查詢時遇到麻煩,該查詢針對不同表中的答復數量獲取排序論壇主題。 我在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
它給我這是一個錯誤:
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個,這是我所期望的。
這是因為子句順序錯誤。
這是正確的語法( 在下面的每個評論中進行編輯 ):
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
子句才有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.