2012-11-30 209 views
1

我有一個sql查詢運行速度非常慢,我對爲什麼感到困惑。查詢內容爲:MySQL查詢運行*非常*緩慢

SELECT DISTINCT(c.ID),c.* FROM `content` c 
    LEFT JOIN `content_meta` cm1 ON c.id = cm1.content_id 
WHERE 1=1 
    AND c.site_id IN (14) 
    AND c.type IN ('a','t') 
    AND c.status = 'visible' 
    AND (c.lock = 0 OR c.site_id = 14) 
    AND c.level = 0 
    OR 
     (
      ( c.site_id = 14 
      AND cm1.meta_key = 'g_id' 
      AND cm1.meta_value IN ('12','13','7') 
     ) 
      OR 
      ( c.status = 'visible' 
      AND ( 
        (c.type = 'topic' AND c.parent_id IN (628,633,624)) 
       ) 
     ) 
     ) 
ORDER BY c.date_updated DESC LIMIT 20 

內容表大約有1250行,內容元表大約有3000行。這不是很多數據,我不太確定可能導致它運行得如此緩慢。任何想法/意見將不勝感激。

謝謝!

+1

使用'explain'來查看性能缺失的位置。欲瞭解更多信息,你需要提供更多的信息表結構。 –

+0

以下查詢返回多少條記錄:'select * from content c left join content_meta cm1 on c.id = cm1.content_id'? – mellamokb

+2

你有where子句和按列排序的索引嗎? – Matthew

回答

1

你在哪裏子句正確嗎?您正在進行一系列AND語句,稍後您正在執行OR。

豈不正確的是這樣的:

AND (c.lock = 0 OR c.site_id = 14) 
AND (
     (...) 
     OR 
     (...) 
    ) 

如果它確實是正確的,你能想到在改變結構或在腳本或程序處理的結果。

0

它可能與最終的「OR」子句有關......儘可能使用索引來使用索引,但是最後拋出這個巨大的OR條件可以是任意一個或另一個。不知道更多的底層內容,我會調整內部的UNION,以便每個實體可以利用自己的索引,獲得合格的CID,然後加入最終結果。

select 
     c2.* 
    from 
     (select distinct 
       c.ID 
      from 
       `content` c 
      where 
        c.site_id in (14) 
       and c.type in ('a', 't') 
       and c.status = 'visible' 
       and c.lock in (0, 14) 
       and c.level = 0 
     UNION 
     select 
       c.ID 
      from 
       `content` c 
      where 
        c.status = 'visible' 
       and c.type = 'topic' 
       and c.parent_id in (628, 633, 624) 
     UNION 
     select 
       c.ID 
      from 
       `content` c 
       join `content_meta` cm1 
        on c.id = cm1.content_id 
        AND cm1.meta_key = 'g_id' 
        AND cm1.meta_value in ('12', '13', '7') 
      where   
        c.site_id = 14) PreQuery 
     JOIN `content` c2 
     on PreQuery.cID = c2.cID 
    order by 
     c2.date_updated desc 
    limit 
     20 

我將確保內容表上(PARENT_ID,類型,狀態)

和元表上(的content_id,meta_key,meta_value的指數(SITE_ID,類型,狀態)的另一個指標)