我的数据库中有以下表格:
thread --- thread_replies ---回复 thread --- thread_tags --- tags
thread: id, title, content, created, author_id
thread_tags: id, thread_id, tag_id
tags: id, name
我可以使用以下选项为某个线程选择标签:
SELECT GROUP_CONCAT(DISTINCT tags.name ORDER BY tags.name DESC SEPARATOR ',') AS tags
FROM tags INNER JOIN thread_tags ON tag_id = tags.id
INNER JOIN thread ON thread_id = thread.id
WHERE thread.id = 20
但是,我想要做的是当我选择所有线程时,我想选择与每个线程关联的所有标签...
我想构建一个多维数组,如下所示:
Array
(
[t_id] => 20
[title] => this is a title
[content] => This is content
[username] => username1
[a_id] => 35
[tags] => tag1, tag2, tag3
)
我想知道我可以用什么sql语句为每个线程创建它?
因此,如果我选择所有线程及其相关作者,我怎样才能获得与每个线程关联的标签?
目前我用它来获取每个帖子及其作者:
SELECT thread.id AS t_id, thread.title,
thread.content, author.username, author.id AS a_id
FROM thread INNER JOIN author ON thread.author_id = author.id
答案 0 :(得分:0)
我认为这应该有效:
SELECT distinct thread.title, thread.id as t_id, thread.content, author.username, author.id as a_id,
GROUP_CONCAT(DISTINCT tags.name ORDER BY tags.name DESC SEPARATOR ',') AS tags
from thread join thread_tags on thread.id = thread_tags.thread_id
join tags on thread_tags.tag_id = tags.id
inner join author on author.id = thread.author_id
group by thread.title