2014-11-25 79 views
1

該查詢起作用。使用10.000個生產線時,需要11秒。如果我不使用ORDER BY,它只需要1秒。但我需要ORDER BY。SQL優化 - 查詢需要11秒

我們可以優化它嗎?

SELECT 
    u.urunID, 
    i.urunadi, 
    u.seo, 
    u.stok_kodu, 
    u.kstok_sayisi, 
    u.stok_sayisi, 
    u.goruntuleme, 
    (SELECT SUM(su.adet) FROM siparis_urunler su LEFT JOIN siparis s ON s.siparisID = su.siparisID WHERE s.durum_id NOT IN (26, 24) AND su.urunID = u.urunID) AS sadet 
FROM 
    urunler u 
INNER JOIN urun_isim i ON u.urunID = i.urunID 
WHERE 
    u.stok_sayisi <= u.kstok_sayisi 
AND u.durum = 1 
GROUP BY 
    u.urunID 
ORDER BY 
    sadet DESC 
LIMIT 0, 20 

說明:

+----+--------------------+-------+--------+---------------------------------+-----------+---------+-----------------------------+------+----------------------------------------------+ 
| id | select_type  | table | type | possible_keys     | key  | key_len | ref       | rows | Extra          | 
+----+--------------------+-------+--------+---------------------------------+-----------+---------+-----------------------------+------+----------------------------------------------+ 
| 1 | PRIMARY   | i  | index | PRIMARY,urunadi2    | urunadi | 768  | NULL      | 4997 | Using index; Using temporary; Using filesort | 
| 1 | PRIMARY   | u  | eq_ref | PRIMARY,urunID,urunler,urunler2 | PRIMARY | 4  | katalog_db.i.urunID   | 1 | Using where         | 
| 3 | DEPENDENT SUBQUERY | sp | ALL | NULL       | NULL  | NULL | NULL      | 11 | Using where         | 
| 2 | DEPENDENT SUBQUERY | s  | ALL | PRIMARY,siparis     | NULL  | NULL | NULL      | 805 | Using where         | 
| 2 | DEPENDENT SUBQUERY | su | ref | surunler2      | surunler2 | 10  | katalog_db.s.siparisID,func | 1 | Using where         | 
+----+--------------------+-------+--------+---------------------------------+-----------+---------+-----------------------------+------+----------------------------------------------+ 
+0

你有'sadet'索引嗎? – Siyual 2014-11-25 15:02:53

+0

在此查詢前加上說明並用結果編輯您的問題。同時添加表格定義。 – Mihai 2014-11-25 15:04:35

+0

刪除我的第一個答案。問:你選擇sum()和left-join在siparis上有一個WHERE子句,強制它成爲INNER JOIN。你能否澄清SIPARIS_URUNLER和SIPARIS的關係及其僅查找除DURUM_ID 24或26之外的所有用戶的關係? – DRapp 2014-11-25 16:23:17

回答

1

這是否跑得更快?

SELECT 
    u.urunID, 
    i.urunadi, 
    u.seo, 
    u.stok_kodu, 
    u.kstok_sayisi, 
    u.stok_sayisi, 
    u.goruntuleme, 
    SUM(su.adet) AS sadet 

FROM 
    urunler u 
    INNER JOIN urun_isim i  ON u.urunID = i.urunID 
    INNER JOIN siparis_urunler su ON su.urunID = u.urunID 
    LEFT JOIN siparis s   ON s.siparisID = su.siparisID 

WHERE 
    u.stok_sayisi <= u.kstok_sayisi 
    AND s.durum_id NOT IN (26, 24) 
    AND u.durum = 1 
GROUP BY 
    u.urunID, 
    i.urunadi, 
    u.seo, 
    u.stok_kodu, 
    u.kstok_sayisi, 
    u.stok_sayisi, 
    u.goruntuleme 
ORDER BY 8 DESC 
+0

嘿@hashbrown它需要11秒。現在需要0.027秒。非常感謝你! – yavuzkirez 2014-11-26 12:05:21

+0

很高興在這裏!這是一個非常好的改進。 – hashbrown 2014-11-26 12:58:52