我有这个查询需要大约40-50秒来加载
SELECT
members.latitude,
members.longitude,
members.mem_id
FROM members
WHERE profile_type != "C"
AND (gender = 'm'
OR gender = 'f')
AND members.mem_id IN(SELECT DISTINCT
n2.mem_id
FROM network n1,
network n2
WHERE n1.frd_id = n2.mem_id
AND n1.mem_id = '48'
AND n2.frd_id = '48')
ORDER BY profilenam
有包含用户朋友的网络表
请帮助..
答案 0 :(得分:3)
这很慢因为使用了子查询而没有使用派生表进行子查询:
SELECT latitude, longitude, a.mem_id
FROM members a
INNER JOIN (SELECT DISTINCT n2.mem_id AS mem_id
FROM network n1,
network n2
WHERE n1.frd_id = n2.mem_id
AND n1.mem_id = '48'
AND n2.frd_id = '48'
) b
ON a.mem_id = b.mem_id
WHERE profile_type != "C"
AND (gender = 'm'
OR gender = 'f')
ORDER BY profilenam;
还要在表上添加适当的索引,并使用EXPLAIN EXTENDED
检查索引使用情况:
ALTER TABLE network ADD KEY ix1(mem_id);
ALTER TABLE network ADD KEY ix1(frd_id);
答案 1 :(得分:0)
如果结果集很小,IN子句才真正适用。对于更大的结果集,请考虑重写查询。过滤器(IN子句生成的过滤器)是一种昂贵的数据库操作。
答案 2 :(得分:0)
用EXISTS替换IN子句。
IN集合中只允许1000项
在(items_num = 1000)