Once again a question about mysql with my small database to practise with:
I got the tables as followed:
Songs Link Tags
======= ===== =======
Sid Sid Tid
Songname Tid Tagname
Now what I am trying to do is once i query (or search for) a song with entering some tags, to display how many tags that song has to create a match percentage.
Thanks to the awesome stackoverflow community i got the query
SELECT s.Sid, s.Songname
FROM Songs s
JOIN Link l ON ( l.Sid = s.Sid )
JOIN Tags t ON ( t.Tid = s.Tid )
WHERE t.Tagname IN ( 'X', 'Y' )
GROUP BY s.Sid, s.Songname
HAVING COUNT(1) = 2
Which searches for songs that match exactly these 2 tags.
Suppose now you’ve got this song A which has tag G, X, Y, and Z.
The query finds this song because it has X and Y in it.
However the song got 2 others, thus I want to create (with php) a match % showing 50% for this one.
I don’t have any trouble with the php part, but i cant figure out a query to get all songs that match these tags along with their total amount of tags in one result set.
Cheers!
Edit1:
I noticed that most of the answers show what I’ve already tried. So i’ll make another more deep example:
Suppose you’ve got the following 4 songs:
A with tags A, B, X and Y
B with tags A, B, C, D, E, X, Y
C with tags A, B, C, D, F, X
D with tags X and Y
Now the query for searching songs with tags X and Y is enterred. I want the following output:
TotalNumberOfTags: Song:
4 A
7 B
2 D
C didn’t have X AND Y so he falls out.
Edit2:
To illustrate i want to use the query
SELECT COUNT(t.Tagname) FROM FROM Songs s
JOIN Link l ON ( l.Sid = s.Sid )
JOIN Tags t ON ( t.Tid = s.Tid )
WHERE s.Songname="A"
on the whole returning set of songnames caused by the queries above, in one query to use ORDER BY COUNT(t.Tagname) ASC on the set.
The answer i found is a work around but it works.
I create a temporary table like this
which i fill with the 2 separate queries i displayed in my question.
Then with with a simple query
I receive all songs with their total number of tags, which i display one by one.
After i close the connection in php this temporary table automatically get’s removed, so no hassling about that.