2015-09-27 150 views
0

需要一些查询帮助。 在数据库中有〜700k图像,每个图像都有自己的标签。 我希望能够使用全文搜索查询按标签搜索图片。 该查询完全符合我的要求,但速度很慢。 有些人可以帮助我加快速度,或创建另一个。 在'image_tag'表中的id字段和名称字段中存在索引。缓慢的mysql查询全文搜索标签数据库

SELECT 
    image.* 
FROM image 
INNER JOIN (SELECT image_to_tag.image_id, 
      GROUP_CONCAT(image_tag.`name`) AS tags 
     FROM image_to_tag 
     INNER JOIN image_tag 
     ON (image_tag.id = image_to_tag.image_tag_id) 
    GROUP BY image_to_tag.image_id) t ON t.image_id = image.id 
WHERE MATCH (t.tags) AGAINST ('+justin* +backgrounds*' IN BOOLEAN MODE) 

表:图像

id | filename 
1 | image1.jpg 
2 | image2.jpg 
3 | image3.jpg 

表:image_to_tag

image_id | image_tag_id 
1  | 1 
1  | 2 
2  | 3 
2  | 4 

表:IMAGE_TAG

id | name 
1 | justin bieber 
2 | backgrounds 
3 | justin timberlake 
4 | other backgrounds 

如果我搜索 “贾斯汀背景” 我想找到图像1和2. 如果我搜索“贾斯汀·比伯背景”,我想查找图片1.

+0

首先,避免在查询中使用'*'。 – RubahMalam

+0

已经尝试过,但它没有太大帮助,0.1秒。 –

回答

0

请试试这个,让我知道如果这可能会更快一点。

select id,filename from image 
where id in(
    select image_id from image_to_tag a 
    inner join image_tag b 
    on b.id = a.image_tag_id and b.name like '%justin%' 
) 
+0

它从1.7秒变为1.4秒。 –

+0

@MichaelvandeRijt这是我知道的最快的方式。考虑在http://dba.stackexchange.com/questions/tagged/performance上询问这个问题。 – RubahMalam

+0

刚发布它,希望有人能帮助我。谢谢你的帮助! http://dba.stackexchange.com/questions/116291/slow-mysql-query-full-text-search-tag-database –

0

您可以通过将查询拆分为三个部分来提升性能。它会以毫秒为单位给出结果:

$tagids = '';  
$res = $mysqli->query("SELECT group_concat(id) as tagids FROM image_tag WHERE MATCH (name) AGAINST ('+justin* +backgrounds*' IN BOOLEAN MODE"); 
if($row = $res->fetch_object()){ 
    $tagids = $row->tagids; 
} 
$res->close(); 

$imageids = ''; 
$res = $mysqli->query("SELECT group_concat(image_id) as imageids FROM image_to_tag WHERE image_tag_id in($tagids)"); 
if($row = $res->fetch_object()){ 
    $imageids = $row->imageids; 
} 
$res->close(); 

$imgarr = array(); 
$res = $mysqli->query("SELECT id,filename FROM image WHERE id in($imageids)"); 
if($row = $res->fetch_object()){ 
    array_push($imgarr,$row); 
} 
$res->close(); 
echo json_encode($imgarr);