2014-11-02 289 views
0

我有以下查詢,我正在使用這兩個運算符來獲取具有特定數字之間的年齡的記錄,但查詢花了很多時間來顯示結果,其鴨舌超過5分鐘仍運行查詢花費很長時間執行

SELECT 
    *, 
    (SELECT COUNT(*) 
    FROM users 
    WHERE 
    1=1 OR 
    LOWER(age) BETWEEN 18 AND 20 OR 
    LOWER(age) BETWEEN 20 AND 25 OR 
    LOWER(age) BETWEEN 25 AND 30 OR 
    LOWER(age) BETWEEN 30 AND 35 
) AS totalcount 
FROM users, states, countries, user_types, media 
WHERE 
    users.id_user_type = user_types.id AND 
    users.id_state = states.id AND 
    users.id_country = countries.id AND 
    media.id_user = users.id AND 
    media.profile_photo = 1 AND 
    users.id_user_type = 3 OR 
    LOWER(age) BETWEEN 18 AND 20 OR 
    LOWER(age) BETWEEN 20 AND 25 OR 
    LOWER(age) BETWEEN 25 AND 30 OR 
    LOWER(age) BETWEEN 30 AND 35 
ORDER BY users.id 

令人不安的部分是:使用or條款你有(它沒有意義)

LOWER(age) BETWEEN 18 AND 20 OR 
LOWER(age) BETWEEN 20 AND 25 OR 
LOWER(age) BETWEEN 25 AND 30 OR 
LOWER(age) BETWEEN 30 AND 35 
+0

你是什麼試圖用這個查詢來檢索? – 2014-11-02 12:57:24

+0

你怎麼得出這樣的結論:查詢的那一部分是令人不安的部分? – Guffa 2014-11-02 12:57:29

回答

1

避免。你的查詢可能做了很多CROSS JOIN操作,這就是爲什麼它需要很長時間(你的結果集很大)。

select *, 
     (
      select count(*) 
       from users 
      where 1=1 
       or lower(age) between 18 and 20 
       or lower(age) between 20 and 25 
       or lower(age) between 25 and 30 
       or lower(age) between 30 and 35 
     ) as totalcount 
    from users, states, countries, user_types, media 
    where users.id_user_type = user_types.id 
    and users.id_state = states.id 
    and users.id_country = countries.id 
    and media.id_user = users.id 
    and media.profile_photo = 1 
    and users.id_user_type = 3 
    order by users.id 

此外,目前還不清楚你試圖用這個查詢來完成什麼。

回答這些問題可以幫助我們來幫您:

  1. 有什麼age列類型
  2. 你到底是從內部查詢
+2

WHERE 1 = 1'和所有其他'BETWEEN'語句怎麼樣?爲什麼使用LOWER年齡),年齡是一個字符串嗎?爲什麼要把它和數字比較呢?我認爲你應該解決這些問題,當它說「它沒有意義」時。 – wolfgangwalther 2014-11-02 13:02:21

0

or語句解析不正確期待什麼。您需要括號:

FROM users, states, countries, user_types, media 
WHERE (users.id_user_type = user_types.id AND 
     users.id_state = states.id AND 
     users.id_country = countries.id AND 
     media.id_user = users.id AND 
     media.profile_photo = 1 AND 
     (users.id_user_type = 3 OR 
     LOWER(age) BETWEEN 18 AND 20 OR 
     LOWER(age) BETWEEN 20 AND 25 OR 
     LOWER(age) BETWEEN 25 AND 30 OR 
     LOWER(age) BETWEEN 30 AND 35 
     ) 

書面,查詢所要做的五個表中一個完整的笛卡爾乘積,然後做一些怪異的過濾。

如果您使用適當的join語法,這基本上是一個非問題。簡單的規則:切勿在from子句中使用逗號。

另外,查詢似乎沒有意義。爲什麼要將age作爲字符串存儲(如使用lower()建議的那樣?那麼,爲什麼要將這些與整數進行比較?爲什麼要將連續範圍分成四個不同的比較,而不是僅僅說age between 18 and 35