-1

I have this table tagMusic

id   tagid   musicid
---------------------
1     1       141
2     4       141
3     3       102

So I need to say: take me all the music ID who have tag Id 1 AND 4 (for example ).

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Raph
  • 123
  • 2
  • 11

1 Answers1

1

One way about it is to select only those tags and count how many unique results you got per tag:

SELECT   musicid
FROM     tagmusic
WHERE    tagid IN (1, 4)
GROUP BY musicid
HAVING   COUNT(*) = 2 
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • OMG It was so simple, I've a last question, Has what serves HAVING COUNT ? – Raph Aug 30 '15 at 21:35
  • `having` is a conditional clause that applies **after** the `group by`, so you can use it to filter aggregate expressions. Here, I use it to filer `musicid`s that have **both** tags (a count of 2), in order to remove `musicid`s that have just `tagid` of 1 or of 4. – Mureinik Aug 30 '15 at 21:37
  • I'm trying but this in a good solution in that case, but my table is extensible, and I'll have more than 2 tag for 1 music... – Raph Aug 30 '15 at 21:44
  • Just change the conditions in the `where` and `having` clauses accordingly. – Mureinik Aug 30 '15 at 21:47