tags:

views:

28

answers:

1

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

+1  A: 

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';
klennepette
Does not do what I want, it will give me all thread linked to at least one of the tags, I want only threads linked to all tags (precised in the question).
Serty Oan
Sorry, I read it wrong. I'd probably do it the same way you did. However if you'd like to look further into this maybe you can take a look at mysql's GROUP_CONCAT function: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat I think it's possible, I'm going to check into it for a bit, if i find somethig i'll update the answer.
klennepette
Thanks. That's interesting. Any idea of the difference of performance ?
Serty Oan
Not sure on the difference, but I've noticed it doesn't work.It only works when the tags are sequential, and if no numbers are missing. So if a Thread has tags 1,2,4,5,6 and you want to check for tags 1,2,5,6 it won't match.
klennepette
It will work, just need to add a condition on the join to search only lines with the tag ids I'm looking for.
Serty Oan