2011-04-03 68 views
1

你怎麼能加入這些5桌一起:選擇某些標籤的帖子及其作者

tag: id, name 
author: username, id 
thread_tags: thread_id, tag_id 
thread: id, content 
author_threads: author_id, thread_id 

(我也有一個表稱爲author_tags(TAG_ID,AUTHOR_ID),但我不認爲這裏需要的多數民衆贊成)。

我想選擇標記某個標記及其作者的所有線程。

下面的代碼返回#1066 - Not unique table/alias: 'tag'

SELECT thread.content, author.username 
FROM tag 
JOIN thread_tags ON thread.id = thread_tags.thread_id 
JOIN tag ON thread_tags.tag_id = tag.id 
JOIN author_threads ON author.id = author_threads.author_id 
JOIN author ON author_threads.thread_id = thread.id 
WHERE tag.name = 'arsenal' 

編輯:

這工作:

SELECT thread.content 
FROM tag 
JOIN thread_tags ON tag.id = thread_tags.tag_id 
JOIN thread ON thread.id = thread_tags.thread_id 
WHERE tag.name = 'tagged' 
LIMIT 0 , 30 

然而,每當我試圖加入的作者與他們的線程,它拋出#1066錯誤。

回答

0

您已經加入tag表兩次,(因此錯誤),並沒有加入thread表。

SELECT thread.content, author.username 
FROM tag 
    JOIN thread_tags 
    ON tag.id = thread_tags.tag_id 
    JOIN thread         --join thread (not tag again) 
    ON thread.id = thread_tags.thread_id 
    JOIN author_threads 
    ON author_threads.thread_id = thread.id  --error here too, in your query 
    JOIN author 
    ON author.id = author_threads.thread_id  --error here too, in your query 
WHERE tag.name = 'arsenal' 
+0

同意其中一個'標籤'應該是'線程',但我認爲它必須是第一個。 (你可以看到'thread'在第一個連接條件中被引用的事實。) – 2011-04-03 12:12:48

+0

@Andriy:是的,如果我們想做最小的改變(並且查詢工作!),我們必須改變第一個'tag' - >'thread'並且交換最後兩個'ON ...'的條件。 – 2011-04-03 16:53:43

0

爲什麼你的JOIN中有一個標籤表?這就是爲什麼你所得到的錯誤:

JOIN tag ON thread_tags.tag_id = tag.id 

你也有表標籤瀏覽:

FROM tag 

變量表出現了兩次。

0

查詢中有兩次標記表。也許這就是問題所在。

+0

它應該是什麼? – 2011-04-03 19:02:44

0
SELECT thread.content, author.username 
FROM thread 
LEFT JOIN thread_tags ON thread.id = thread_tags.thread_id 
LEFT JOIN tag ON thread_tags.tag_id = tag.id 
LEFT JOIN author_threads ON author.id = author_threads.author_id 
LEFT JOIN author ON author_threads.thread_id = thread.id 
WHERE tag.name = 'arsenal' 

順便說一句 - 是不是更好地存儲author_id`` in線程表?

+0

「*將'author_id'存儲在'thread'表中* *'不是更好嗎?不是如果一個線程可以有很多作者,就像表結構所建議的那樣。 – 2011-04-03 08:46:36

+0

#1054 - 'on子句'中的未知列'author.id' – 2011-04-03 19:10:46

相關問題