选择某些标记的帖子及其作者

时间:2011-04-03 08:23:38

标签: mysql sql join mysql-error-1066

如何将这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 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

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

JOIN tag ON thread_tags.tag_id = tag.id

你这里也有表格标签:

FROM tag

标签表出现了两次。

答案 2 :(得分:0)

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

答案 3 :(得分: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'

BTW - 存储author_id`` in线程表是不是更好?