0

我有一张包含 540 万条记录的表(产品)。如果我使用下面的查询来获得结果,但它的工作速度很慢。有没有更有效的方法?

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 
4

3 回答 3

1

in旧版本的 MySQL 在子查询优化方面做得很差。如果您知道searchkwdmgmt每条记录最多有一个关键字匹配,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(*) = 1 
        LIMIT  0, 31
       ) q join
       searchdetails sd 
       ON sd.imageid = q.imageid ;

如果可以有多个关键字匹配并且表中有一个idproduct您可以执行以下操作:

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).

于 2013-08-10T20:12:35.610 回答
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')

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

于 2013-08-10T19:50:58.680 回答
1

在下面的列上创建索引

1.列:allkwd 表:searchkwdmgmt

2.Column:imageid 表:searchdetails

3.Column:imageid 表:product

4.避免使用In子句

于 2013-08-10T18:59:11.273 回答