Scarface
Scarface

Reputation: 3923

search for results with the most tags in common

I am trying to do an sql query or set of queries that will allow me to find other videos that have the same tags and order them by the most number of matches. I am using php as a server side code and mysql as my database. For this I am using 2 tables.

video

  Column    Type           Null 
     timestamp  int(11)     No       
     vid_id     varchar(32) No       
     file_name  varchar(32) No       
     uploader   varchar(55) No       
     title      varchar(30) No       
     duration   varchar(7)  No       

    Keyname Type     Unique Packed  Column  Cardinality Collation
    vid_id  BTREE    Yes    No      vid_id         94       A       
    title   FULLTEXT No     No       title              0

tags

 Column      Type      Null 
     id     varchar(35) No       
     vid_id varchar(35) No       
     name   varchar(15) No       

    Keyname Type    Unique  Packed  Column  Cardinality Collation
    vid_id  BTREE   Yes      No     vid_id      0      A        
    name    FULLTEXT No      No     name        0

One vid_id will be supplied for the query. I really am not sure what the best way to approach this would be so any expert opinion would really be appreciated.

Upvotes: 1

Views: 116

Answers (1)

Rob
Rob

Reputation: 1885

I would do a

SELECT vid_id, COUNT(*) as count 
   FROM tags 
   WHERE name IN('list','of','videos','tags') 
   GROUP BY vid_id
   ORDER BY count DESC

If you choose to employ the method in my comment above, this would be slightly more complicated.

You would need first

SELECT id FROM tags WHERE name IN('list','of','video','tags')

then, using those tag ids

SELECT vid_id, COUNT(*) as count
   FROM tags_videos
   WHERE tag_id IN(list,of,tag,ids)
   GROUP BY vid_id
   ORDER BY count DESC

You could probably still do it in one query, but it would use some ugly joins, and the speed difference probably wouldn't be TOO significant.

Upvotes: 1

Related Questions