One thing you could improve ... Instead of writing x = a OR x = b OR x = c , you can shorten it to this: x IN (a, b, c) .
SELECT movies.title FROM movies,keywords_table WHERE keywords_table.key_id IN ($key_id[1], $key_id[2], ..., $key_id[n])
Please note that there is no join condition in your request. You are currently making CROSS JOIN, also known as a decartive product. I think you want this:
SELECT movies.title FROM movies JOIN keywords_table ON movies.id = keywords_table.id WHERE keywords_table.key_id IN ($key_id[1], $key_id[2], ..., $key_id[n])
This query can return the same movie more than once, so you can add DISTINCT to remove duplicates. You can also do everything in one request instead of two as an additional optimization:
SELECT DISTINCT M.title FROM keywords_table K1 JOIN keywords_table K2 ON K2.key_id = K1.key_id JOIN movies M ON K2.id = M.id WHERE K1.id = 4
As far as performance is concerned, make sure that you have set the primary key (id) to movies and (key_id, id) to keywords_table .
Mark byers
source share