开发者

Selecting certain tagged posts and their authors

How can you join these 5 tables together:

tag: id, name
author: username, id
thread_tags: thread_id, tag_id
thread: id, content
author_threads: author_id, thread_id

(I also have a table called author开发者_StackOverflow社区_tags (tag_id, author_id), but I dont think thats needed here).

I want to select all the threads which are tagged a certain tag and their authors.

The following code returns #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'

EDIT:

This works:

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

However whenever I try to join authors with their threads, it throws #1066 errors.


You have joined the tag table twice, (thus the error) and haven't joined the thread table.

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'


why you have a tag table in your JOIN? this is why you are getting the error:

JOIN tag ON thread_tags.tag_id = tag.id

you also have table tag here:

FROM tag

tag table appeared twice.


You have the tag table twice in your query. Maybe that's the problem.


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 - isn't it better to store author_id`` inthread` table ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜