簡體   English   中英

如何提高嵌套的mysql查詢速度,比如這個?

[英]How can I improve nested mysql query speed such as this one?

我在執行此類查詢時從mysql服務器檢索快速響應時遇到一些困難:

select distinct(products.id) as product_id,products.title as product_name, (select count(id) from stock where stock.available='0' and stock.product_id=products.id) as none,
(select count(id) from stock where stock.available='1' and stock.product_id=products.id) as available,
(select count(id) from stock where stock.available='2' and stock.product_id=products.id) as staged,
(select count(id) from stock where stock.available='3' and stock.product_id=products.id) as departed,
(select count(id) from stock where stock.available='4' and stock.product_id=products.id) as delivered
from products,stock where products.id=stock.product_id;

我想知道是否有任何其他查詢方法可以提供更快的響應。 Thanx :-)

像這樣的東西:

SELECT
  P.id as product_id,
  P.title as product_name,
  SUM(CASE WHEN S.available = 0 THEN 1 ELSE 0 END) as none,
  SUM(CASE WHEN S.available = 1 THEN 1 ELSE 0 END) as available,
  SUM(CASE WHEN S.available = 2 THEN 1 ELSE 0 END) as staged,
  SUM(CASE WHEN S.available = 3 THEN 1 ELSE 0 END) as departed,
  SUM(CASE WHEN S.available = 4 THEN 1 ELSE 0 END) as delivered 
FROM products P
      JOIN stock S
          ON P.id = S.product_id
    GROUP BY P.id,
             P.title

暫無
暫無

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

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