簡體   English   中英

加快緩慢的MySQL SubQuery更新

[英]Speeding Up a slow MySQL SubQuery Update

我有以下UPDATE腳本,該腳本可對我的站點上的活動產品進行計數,因此我可以快速參考類別中是否有產品,而無需在前端進行此計數。

UPDATE category_to_store
SET products = (
                SELECT COUNT(*)
                FROM product p 
                LEFT JOIN product_to_category p2c 
                     ON (p.product_id = p2c.product_id) 
                LEFT JOIN product_to_store p2s 
                     ON (p.product_id = p2s.product_id) 
                WHERE p.status = '1' 
                AND p.date_available <= NOW()
                AND p2c.category_id = category_to_store.category_id
                AND p2s.store_id = category_to_store.store_id
               );

我使用的表格說明如下:

DESCRIBE category_to_store;

Field       Type        Null    Key     Default Extra 
---------------+---------------+-------+-------+-------+---------------
category_id int(11)     NO  PRI     
store_id    int(11)     NO  PRI     
products    int(11)     NO      0   

DESCRIBE product;

Field       Type        Null    Key     Default Extra 
---------------+---------------+-------+-------+-------+---------------
product_id  int(11)     NO  PRI     auto_increment
~
date_available  date        NO          
~
status      tinyint(1)  NO      0               
~

DESCRIBE product_to_category;

Field       Type        Null    Key     Default Extra 
---------------+---------------+-------+-------+-------+---------------
product_id  int(11) NO  PRI     
category_id int(11) NO  PRI     

DESCRIBE product_to_store;

Field       Type        Null    Key     Default Extra 
---------------+---------------+-------+-------+-------+---------------
product_id  int(11) NO  PRI     
store_id    int(11) NO  PRI 0

product表中有我尚未包括但尚未使用的字段)

目前,該程序可以正常運行,但目前需要110秒。

我已將網站設置為使用WHERE category_to_store.category_id = '(int)'來限制查詢,但這意味着找出可能會受到更新影響的類別,我猜這是可行的,但我想知道你們中的任何一個是否可愛天才有我錯過的更好的解決方案?

先感謝您。

如果要更新很多行,則執行連接可能比使用“嵌套循環”操作更有效。

   UPDATE category_to_store cts
     LEFT 
     JOIN (
            SELECT COUNT(*) AS cnt_
                 , p2c.category_id
                 , p2s.store_id
              FROM product p
              LEFT
              JOIN product_to_category p2c
                ON (p.product_id = p2c.product_id)
              LEFT
              JOIN product_to_store p2s
                ON (p.product_id = p2s.product_id) 
             WHERE p.status = '1'
               AND p.date_available <= NOW()
             GROUP
                BY p2c.category_id
                 , p2s.store_id
          ) c
         ON c.category_id = cts.category_id
        AND c.store_id = cts.store_id
        SET cts.products = IFNULL(c.cnt_,0)

為了獲得最佳性能,您需要合適的索引,可以考慮添加索引,例如

 ... ON product (product_id, status, date_available)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM