2011-01-06 18 views
0

Ich habe die folgenden Tabellen in meiner Datenbank:Tagging in PHP und SQL

Thread --- --- thread_replies antwortet Thread --- thread_tags --- Tags

thread: id, title, content, created, author_id 

thread_tags: id, thread_id, tag_id 

tags: id, name 

ich wählen kann Tags für einen bestimmten Thread folgendes mit:

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 

aber was ich tun möchte, ist, wenn ich alle Fäden wählen, möchte ich auch mit jedem Thread zugeordnet alle Tags wählen ...

Ich möchte ein mehrdimensionales Array wie folgt aufzubauen:

Array 
(
    [t_id] => 20 
    [title] => this is a title 
    [content] => This is content 
    [username] => username1 
    [a_id] => 35 
    [tags] => tag1, tag2, tag3 
) 

ich wissen will, welche SQL-Anweisung ich dies für jeden Thread erstellen können?

Also, wenn ich alle Threads und ihre zugehörigen Autoren auswähle, wie bekomme ich auch die Tags mit jedem Thread verbunden?

Zur Zeit benutze ich diese jeden Thread und seinen Autor zu erhalten:

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 

Antwort

0

Ich denke, das sollte funktionieren:

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