我正在使用以下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'
我有以下表格:
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。
答案 0 :(得分:3)
原始查询中CROSS JOIN
,thread
和author
之间存在隐式reply
,并且第二次加入相同的表而没有别名。
使用此:
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 :(得分: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'
答案 2 :(得分:1)
您在FROM
子句中包含表格,然后加入他们 - 我认为您只想FROM thread
,然后加入。
答案 3 :(得分:0)
您在
行上显示错误JOIN author_reply ON thread.id = author_reply.thread_id
根据给定的定义,你的author_reply表中没有thread_id。
答案 4 :(得分: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'