Currently, my current MySQL query takes up to 10 seconds to run in my application:
SELECT tagid, tag FROM tags WHERE tagid IN
(SELECT DISTINCT tagid FROM news_tags WHERE newsid IN
(SELECT newsid FROM news_tags WHERE tagid IN (16,32)
GROUP BY newsid HAVING COUNT(newsid)>=2))
AND tagid NOT IN (16,32) ORDER BY level, tagid
Used tables:
- table
news_tags, with columns newsid,tagid - a table
tagswith columns tagid, tag,level
The purpose of the query is to find news items tagged with tags tagid16 and 32, and then find other tags for which news tags have also been tagged, in order to provide the user with the opportunity to narrow down the “news” items with more specific tag combinations. The ultimate goal is to capture the remaining relevant columns from tagand tagidfrom the table tags.
I tried to make different equivalent attempts JOIN, but could not select all those remaining tagidin the news that have tags attached to them.
Here are my SQL EXPLAINSQL results if they point to another reason for the slowness that I skip:
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | PRIMARY | tags | range | PRIMARY | PRIMARY | 4 | NULL | 55 | Using where; Using filesort
2 | DEPENDENT SUBQUERY | news_tags | index_subquery | tagid | tagid | 4 | func | 26 | Using index; Using where
3 | DEPENDENT SUBQUERY | news_tags | index | tagid | PRIMARY | 8 | NULL | 11 | Using where; Using index
, : , BOTH 16 32, 16 32. .