简体   繁体   中英

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_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`` in thread` table ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM