我知道IN,NOT in in mysql查询(不推荐使用)不是性能明智的,但这是我需要实现的。还有其他方法可以更好地实现相同的结果吗? Loc_table是具有id和name的用户列表,表1和2是两个不同的任务表,如果用户完成该特定表的任务,则我在其中注册其他任务(boolean yes no)。下面的查询工作正常,但速度很慢。任何帮助将不胜感激。
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 :(得分: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
答案 1 :(得分: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;