如何快速搜索大表中的记录?

时间:2013-08-10 18:47:02

标签: mysql sql

我有一张表(产品),有540万个recods。如果我使用下面的查询来获得结果,但它的工作非常慢。有更有效的方法吗?

SELECT sd.imageid, sd.licencetype, sd.imgcollection, sd.orientation, 
       sd.pname, sd.pcaption, sd.ptype 
FROM   (SELECT imageid 
        FROM   product 
        WHERE  productkeyword IN (SELECT primary_kwd 
                                  FROM   searchkwdmgmt 
                                  WHERE  allkwd IN ( 'IPhone' )) 
        GROUP  BY imageid 
        HAVING Count(*) = 1 
        LIMIT  0, 31) q 
       JOIN searchdetails sd 
         ON sd.imageid = q.imageid 

3 个答案:

答案 0 :(得分:1)

在以下列上创建索引

  

1.Column:allkwd表:searchkwdmgmt

     

2.Column:imageid表:searchdetails

     

3.Column:imageid表:产品

     

4.避免使用条款

答案 1 :(得分:1)

由于子查询

,这部分很糟糕
SELECT imageid 
FROM product 
WHERE productkeyword IN (SELECT primary_kwd 
                         FROM searchkwdmgmt 
                         WHERE allkwd IN ('IPhone')) 

相同的查询应返回相同的数据,但如果正确设置索引则效率更高。

SELECT
    p.imageid 
FROM
    product as p
INNER JOIN 
    searchkwdmgmt as s ON p.productkeyword = s.primary_kwd 
WHERE 
    s.allkwd IN ('IPhone')

在更换之前先测试一下......

答案 2 :(得分:1)

较早版本的MySQL在使用子查询优化in方面做得很差。如果您知道searchkwdmgmtproduct中每条记录最多只有一个关键字匹配,则可以执行以下操作:

SELECT sd.imageid, sd.licencetype, sd.imgcollection, sd.orientation, 
       sd.pname, sd.pcaption, sd.ptype 
FROM   (SELECT p.imageid 
        FROM product p join
             searchkwdmgmt s
             on p.productkeyword = s.primary_kwd and
                s.allkwd in ( 'IPhone' )
        GROUP  BY p.imageid 
        HAVING Count(*) = 1 
        LIMIT  0, 31
       ) q join
       searchdetails sd 
       ON sd.imageid = q.imageid ;

如果可以有多个关键字匹配且id表中有product,您可以执行以下操作:

SELECT sd.imageid, sd.licencetype, sd.imgcollection, sd.orientation, 
       sd.pname, sd.pcaption, sd.ptype 
FROM   (SELECT p.imageid 
        FROM product p join
             searchkwdmgmt s
             on p.productkeyword = s.primary_kwd and
                s.allkwd in ( 'IPhone' )
        GROUP  BY p.imageid 
        HAVING Count(distinct p.productid) = 1 
        LIMIT  0, 31
       ) q join
       searchdetails sd 
       ON sd.imageid = q.imageid ;

编辑:

使用以下索引,所有这些版本都会更快:searchkwdmgmt(primary_kwd, allkwd)product(productkeyword, imageid)searchdetails(imageid)