Get threads linked to tags
I have 3 tables in my MySQL database :
- the Threads table (id, title)
- the Tags table (id, name)
- the pivot table ThreadTags (tagID, threadID)
Let's admit I already have the tag IDs in array $tagIDs, now I want to have all threads linked to ALL those tags. My current solution is something like that :
$stmt = 'SELECT id, title FROM Threads'."\n";
foreach($tagIDs as $id) {
$stmt .= 'INNER JOIN ThreadTags T1 ON (T1.threadID = Thread.id AND T1.tagID = '.$id.')'."\n";
}
And any number of tags I add another INNER JOIN
to this table.
I think this might work<, I haven't tested this though because I don't have a database nearby.
This doesn't work (see comments)
sort($tagIDs, SORT_NUMERIC);
$tagIDs = implode(',', $tagIDs); // This gives you a string '1,2,5,19'
$stmt = 'SELECT id, title, GROUP_CONCAT( T1.tagID ORDER BY T1.tagid ASC ) as threadtags FROM Threads INNER JOIN
ThreadTags T1 ON T1.threadID
WHERE threadtags LIKE \'%' . $tagIDs . '%\'
GROUP BY Threads.id';
精彩评论