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 错误。

4

4 回答 4

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'
于 2011-04-03T08:27:11.917 回答
0

为什么你的 JOIN 中有一个标签表?这就是您收到错误的原因:

JOIN tag ON thread_tags.tag_id = tag.id

您在这里也有表格标签:

FROM tag

标签表出现了两次。

于 2011-04-03T08:28:04.677 回答
0

您的查询中有两次标签表。也许这就是问题所在。

于 2011-04-03T08:28:47.160 回答
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顺便说一句-存储线程表不是更好吗?

于 2011-04-03T08:28:58.447 回答