我有以下表格:
作者:
id username email password salt email_salt email_verified IP_ADDRESS
Author_threads:
thread_id,author_id
主题:
id,title,content,created
标签:
id,name
Thread_tags:
tad_id,thread_id
我想选择最新的30个主题,他们的作者及其所有标签。这是我使用的SQL语句:
SELECT thread.title, thread.id as thread_id,
thread.content, author.username, author.id as author_id,
GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
GROUP BY thread.id DESC
LIMIT 0, 30
有更简单的方法吗?
答案 0 :(得分:0)
我认为GROUP BY应该是ORDER BY?
除此之外,我确实相信你这样做是正确的。
当您需要所有表中的值时,您需要将它们全部加入,这就是您所做的。
答案 1 :(得分:0)
您唯一的另一个选择是使用多表选择,例如
SELECT thread.title, thread.id as thread_id,
thread.content, author.username, author.id as author_id,
GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
FROM thread, thread_tags, tag, author_threads, author
WHERE thread.id = thread_tags.thread_id
AND thread_tags.tag_id = tag.id
AND thread.id = author_threads.thread_id
AND author_threads.author_id = author.id
GROUP BY thread.id DESC
LIMIT 0, 30
但对此的支持可能与数据库有关。