2011-04-01 89 views
2

我使用下面的SQL語句:同時連接幾個表:

SELECT reply.id, reply.content, author.username 
FROM thread, reply, author 
JOIN thread_reply ON thread.id = thread_reply.thread_id 
JOIN reply ON thread_reply.reply_id = reply.id 
JOIN author_reply ON thread.id = author_reply.thread_id 
JOIN author ON author_reply.author_id = author.id 
WHERE thread.id = '40' 

我有follwing表:

thread_reply: thread_id, reply_id 

reply: id, content, created (timestamp) 

author: id, username, password_hash, salt #etc 

thread: id, content, created 

author_reply: author_id, reply_id 

我不斷收到以下錯誤:

#1066 - Not unique table/alias: 'reply' 

哦,我正在使用MySQL。

+1

你不應該明確從'reply'選擇和'author'如果你要加入他們的行列。 – 2011-04-01 14:18:15

+0

我的頭痛... – 2011-04-01 14:22:56

+1

'thread_reply'和'author_reply'表有什麼意義?一個回覆可以引用多個線程嗎?一個答覆可以有多個作者嗎? – Quassnoi 2011-04-01 14:31:40

回答

1
SELECT reply.id, reply.content, author.username 
FROM thread 
INNER JOIN thread_reply ON thread.id = thread_reply.thread_id 
INNER JOIN reply ON thread_reply.reply_id = reply.id 
INNER JOIN author_reply ON thread.id = author_reply.thread_id 
INNER JOIN author ON author_reply.author_id = author.id 
WHERE thread.id = '40' 
+0

沒有author_reply.thread_id – 2011-04-01 14:29:38

+0

你是對的,它應該是INNER JOIN author_reply ON reply.id = author_reply.reply_id – dcarneiro 2011-04-01 14:39:10

+0

我選擇了這個,因爲它幫助找到正確的答案 – 2011-04-01 14:44:48

3

你有一個隱含的CROSS JOINreply之間threadauthor原始查詢,並且加入第二次相同的表不走樣他們。

使用此:

SELECT reply.id, reply.content, author.username 
FROM thread t 
JOIN thread_reply tr 
ON  tr.thread_id = t.id 
JOIN reply r 
ON  r.id = tr.reply_id 
JOIN author_reply ar 
ON  ar.reply_id = r.id 
JOIN author a 
ON  a.id = ar.author_id 
WHERE thread.id = '40' 
1

要包括的FROM子句中的表,然後加入到他們以及 - 我想你想簡單地FROM thread,然後你的加入。

0

你,說

JOIN author_reply ON thread.id = author_reply.thread_id 

有根據給出的定義在author_reply表中沒有thread_id,則該行得到了一個錯誤。

0

這工作:

SELECT reply.id, reply.content, author.username 
FROM thread 
JOIN thread_reply ON thread.id = thread_reply.thread_id 
JOIN reply ON thread_reply.reply_id = reply.id 
JOIN author_reply ON reply.id = author_reply.reply_id 
JOIN author ON author_reply.author_id = author.id 
WHERE thread.id = '40'