2010-10-12 118 views
0

如何將下面的代碼示例1添加到示例2,而不會搞亂我的查詢。MySQL查詢問題

例1

INNER JOIN users ON users_articles.user_id = users.user_id 

例2

SELECT users.* 
FROM users_articles 
INNER JOIN articles_comments ON users_articles.id = articles_comments.article_id 
INNER JOIN users ON articles_comments.user_id = users.user_id 
WHERE users.active IS NULL 
AND users.deletion = 0 
ORDER BY articles_comments.date_created DESC 
LIMIT 50 

回答

0

如果我理解正確的話,你想加入表users兩次,一次徵求意見,並一度的文章?在這種情況下,你需要別名表。爲了簡潔起見,我通常使用單字母或雙字母的別名,即使我不加倍表時也是如此,但這並不重要。

SELECT ... 
FROM users_articles UA 
INNER JOIN articles_comments AC ON UA.id = AC.article_id 
INNER JOIN users UC ON AC.user_id = UC.user_id 
    AND UC.active IS NULL 
    AND UC.deletion = 0 
INNER JOIN users UA ON UA.user_id = users.user_id 
    AND UA.active IS NULL 
    AND UA.deletion = 0 
ORDER BY AC.date_created DESC 
LIMIT 50 

BTW,不要使用SELECT *,它幾乎總是更好地明確你想要的清單。

免責聲明:我可能誤解了你正在嘗試做的事情;向你的代碼發佈一些上下文通常是一個好主意。在這種情況下,表格名稱讓我感到有些不適(如果這是我的想法,那麼我只是用users,articlescomments)。

+0

我不想顯示文章和其中'users.deletion = 1'的地方 – HELP 2010-10-12 00:34:38

+0

我仍然可以得到它的工作:( – HELP 2010-10-12 00:43:03

+0

它爲什麼不工作?它做什麼?你想要它做什麼? ?上面的代碼也應該拒絕被刪除的用戶,所以我也不太瞭解你的評論, – Amadan 2010-10-12 00:49:42