2016-04-06 131 views
0

我知道,IN,而不是在mysql查詢(這是棄用)不是性能明智的,但這是我需要實現的。還有其他方法可以更好地實現相同的結果嗎? Loc_table是具有ID和名稱的用戶列表,表1和表2是兩個不同的任務表,其中如果用戶定位了特定表的任務(布爾值是否),則我在其中註冊。下面的查詢工作正常,但速度很慢。任何幫助將不勝感激。如何優化此查詢?

loc = mysql_query("SELECT loc_id, name, 
    CASE 
    WHEN loc_id IN (SELECT user_id FROM table 1 WHERE done = 0 GROUP BY loc_id) THEN 1 ELSE 0 
    END AS active_in_1, 
    CASE 
    WHEN loc_id IN (SELECT user_id FROM table2 WHERE done = 0 GROUP BY loc_id) THEN 1 ELSE 0 
    END AS active_in_2 
    FROM loc_table L LEFT JOIN table_2 C ON C.loc_id = L.loc_id LEFT JOIN table_1 A ON A.loc_id = L.loc_id 
    WHERE C.done = 0 OR A.done = 0 GROUP BY loc_id ORDER BY name") or die (mysql_error()); 

回答

0

你不需要在你查詢

SELECT loc_id, name, 
    CASE 
    WHEN A.loc_id is null THEN 0 ELSE 1 
    END AS active_in_1, 
    CASE 
    WHEN c.loc_id is null THEN 0 ELSE 1 
    END AS active_in_1  FROM loc_table L LEFT JOIN table_2 C ON C.loc_id = L.loc_id LEFT JOIN table_1 A ON A.loc_id = L.loc_id 
    WHERE C.done = 0 OR A.done = 0 

哪裏是組功能

GROUP BY loc_id ORDER BY name 
+0

你好rpc!謝謝,我在我的問題中犯了一個錯誤,即時更新它,因爲ID列在任務表中有一個diff名稱,運行查詢給我其他結果 – Aramil

0

好寫另一個查詢,我發現是偶然的解決方案中使用子查詢,它減少執行時間從4秒到40毫秒

select L.loc_id ,L.name, 
CASE 
WHEN (SELECT count(*) from table_1 where user_id = L.loc_id and done = 0) > 0 THEN 1 ELSE 0 
END as active_in_1, 
CASE 
WHEN (SELECT count(*) from table_2 where user_id = L.loc_id and done = 0) > 0 THEN 1 ELSE 0 
END as active_in_2 
FROM loc_table L group by loc_id 
HAVING active_in_1 != 0 OR active_in_2 != 0 
ORDER BY name;