2011-04-03 117 views
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错误。

回答

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' 
+0

同意其中一个'标签'应该是'线程',但我认为它必须是第一个。 (你可以看到'thread'在第一个连接条件中被引用的事实。) – 2011-04-03 12:12:48

+0

@Andriy:是的,如果我们想做最小的改变(并且查询工作!),我们必须改变第一个'tag' - >'thread'并且交换最后两个'ON ...'的条件。 – 2011-04-03 16:53:43

0

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

JOIN tag ON thread_tags.tag_id = tag.id 

你也有表标签浏览:

FROM tag 

变量表出现了两次。

0

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

+0

它应该是什么? – 2011-04-03 19:02:44

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线程表?

+0

“*将'author_id'存储在'thread'表中* *'不是更好吗?不是如果一个线程可以有很多作者,就像表结构所建议的那样。 – 2011-04-03 08:46:36

+0

#1054 - 'on子句'中的未知列'author.id' – 2011-04-03 19:10:46

相关问题