如何使用LEFT JOIN提高LIKE查询速度?

时间:2017-03-22 17:34:39

标签: mysql database

我在查询时间过长(超过7秒)时出现问题。

当我需要进行搜索时,涉及4个表:

  • 分类
  • 标签
  • 视频标签

例如,如果查询是"示例字符串",那么SQL将如下所示:

SELECT DISTINCT v.id v_id, ca.id ca_id, ca.title ca_title, v.title v_title
FROM videos v
JOIN categories ca ON ca.id = v.category_id
LEFT JOIN video_tags vt ON vt.video_id = v.id
LEFT JOIN tags t ON t.id = vt.tag_id
WHERE v.title LIKE "%example%" OR v.title LIKE "%string%" OR
    ca.title LIKE "%example%" OR ca.title LIKE "%string%" OR
    t.name LIKE "%example%" OR t.name LIKE "%string%";

问题在于LEFT JOIN。我在没有它的情况下测试了查询的速度,并且它在不到1秒的时间内返回,但是使用LEFT JOIN,查询将超过7秒。

如何优化此查询以便更快地进行查询。标签表有超过7,000行并且不断增长。它在t.name。

上也有一个UNIQUE索引

编辑1 - 简化架构:

视频:

  • id:varchar(15)[PK]
  • category_id:int [FK]
  • title:varbinary(127)[INDEX]
  • duration:int
  • 描述:BLOB

分类

  • id:int [PK]
  • title:varchar(31)[INDEX]

标签:

  • id:int [PK]
  • name:varchar(255)[UNIQUE]

视频标记:

  • tag_id:int [PK]
  • video_id:varchar(15)[PK]

0 个答案:

没有答案