开发者

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.

Is there a 开发者_如何转开发better way ?

NB : please, no answer like "use a NoSQL database", I can't change that, thanks


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';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜