2011-04-01 4 views
2

J'utilise l'instruction SQL suivante:joindre plusieurs tables à la fois:

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' 

J'ai les tables 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 

Je continue à obtenir l'erreur suivante:

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

Oh et j'utilise MySQL.

+1

Vous ne devez pas sélectionner explicitement de '' reply' et author' si vous allez les rejoindre. –

+0

Ma tête me fait mal ... –

+1

Quel est le but des tables 'thread_reply' et' author_reply'? Peut-on répondre à plusieurs threads? Peut-on répondre à plusieurs auteurs? – Quassnoi

Répondre

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

Il n'y a pas author_reply.thread_id –

+0

vous avez raison, ça devrait être INNER JOIN author_reply ON reply.id = author_reply.reply_id – dcarneiro

+0

J'ai sélectionné ceci parce que ça m'a aidé à trouver la bonne réponse –

3

Vous avez eu une CROSS JOIN implicite entre thread, author et reply dans votre requête d'origine, et se sont joints aux mêmes tables pour la deuxième fois sans les aliasing.

Utilisez ceci:

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

Vous incluez des tables dans la clause FROM puis rejoindre à eux aussi - je pense que vous voulez simplement FROM thread, puis votre joint.

0

Vous avez obtenu une erreur sur la ligne qui dit

JOIN author_reply ON thread.id = author_reply.thread_id 

il n'y a pas thread_id dans votre table de author_reply selon les définitions données.

0

Cela fonctionne:

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'