使大型数据集上的子查询更快

时间:2018-10-02 10:27:02

标签: mysql sql performance

我的数据集很大,我需要帮助来加快一些查询的速度。

到目前为止,我正在使用子查询来检索产品ID,并获得该产品的不同身份的人(类似于过滤功能)

这是我的查询

    SELECT assoc.*, count(assoc.product_id) as count FROM ws_products_persons_assoc as assoc 
        WHERE 
            assoc.product_id 
                IN 
                (   SELECT c.id 
                        FROM ws_products as c 
                    WHERE c.status = '1' 
                        AND ( ( product_name LIKE '%960%' ) OR ( ( code LIKE '%960%' OR isbn13 LIKE '%960%' OR parent_codes LIKE '%960%') ) OR ( publisher_name LIKE '%960%' ) OR ( author_name LIKE '%960%' ) ) 
                    ORDER BY c.year desc,c.product_name ASC 
                ) 

            GROUP BY assoc.person_id    
            ORDER BY count DESC LIMIT 0,30

Query Time =1.7937450408936 seconds

子查询在几个字段中搜索给定的关键字

子查询返回183473行,需要1.7秒的时间来运行。

提出了使子查询更快的任何想法

谢谢

2 个答案:

答案 0 :(得分:0)

我将首先切换到EXISTS

SELECT a.person_id, count(a.product_id) as count
FROM ws_products_persons_assoc a 
WHERE EXISTS (SELECT 1
              FROM ws_products p
              WHERE p.id = a.product_id AND
                    p.status = 1 AND
                    ( (p.product_name LIKE '%960%' ) OR
                      (p.code LIKE '%960%') OR
                      (p.isbn13 LIKE '%960%' OR
                      (p.parent_codes LIKE '%960%') OR
                      (p.publisher_name LIKE '%960%') OR
                      (p.author_name LIKE '%960%' )
                   ) 
            ) 
GROUP BY a.person_id    
ORDER BY count DESC
LIMIT 0, 30;

对于此版本,您希望在ws_products(id, status)上建立索引。

select列应与group by列匹配。

答案 1 :(得分:0)

为什么不进行内部联接? (假设product_id是唯一的)

SELECT a.*, count(a.product_id) as count
FROM ws_products_persons_assoc a INNER JOIN ws_products p
          ON p.id = a.product_id 
WHERE
    p.status = 1 AND
    ( (p.product_name LIKE '%960%' ) OR
    (p.code LIKE '%960%') OR
    (p.isbn13 LIKE '%960%' OR
    (p.parent_codes LIKE '%960%') OR
    (p.publisher_name LIKE '%960%') OR
    (p.author_name LIKE '%960%' )
    ) 

GROUP BY a.person_id    
ORDER BY count DESC
LIMIT 0, 30;