我有一个约会网站,多年来我一直试图优化这个查询。几乎每天网站都因此而陷入困境。
用户表格结构:
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD KEY `multiple_index`(
`unix_timestamp_online`,
`user_blocked`,
`gender`,
`gender_search`,
`maximum_age`,
`minimum_age`,
`birth_year`,
`latitude`,
`longitude`
) USING BTREE;
索引
SELECT id, latitude, longitude
FROM users
WHERE gender=2
AND id NOT IN (11111111,2222222)
AND (birth_year BETWEEN 1961 AND 1999)
AND (latitude BETWEEN -25.14 AND -16.13)
AND (longitude BETWEEN -54.87 AND -45.86)
AND user_blocked=0
AND minimum_age<=35
AND maximum_age>=35
AND gender_search IN(0,1)
ORDER BY unix_timestamp_online DESC
LIMIT 20
查询示例
male=1
总结样本查询的条件..
female=2
并搜索ids
between 1961 AND 1999
latitude, longitude
block=0
... age=35
all=0, male=1
必须为这些用户所接受online
)id: 1
select_type: SIMPLE
table: users
partitions: NULL
type: index
possible_keys: PRIMARY
key: multiple_index
key_len: 19
ref: NULL
rows: 20
filtered: 0.25
Extra: Using where; Using index
解释示例查询
BETWEEN 1999 AND 1999
此查询平均花费0.0020秒
如果我将birth_year条件更改为({{1}})
解释相同,查询平均需要9.1376秒
这个多重索引看起来并不漂亮,但到目前为止它是最好的。任何帮助表示赞赏。谢谢。
答案 0 :(得分:0)
为什么不在复杂的条件之前使用更简单的条件来执行这样的查询。
SELECT id, latitude, longitude
FROM users
WHERE gender=2
AND user_blocked=0
AND minimum_age<=35
AND maximum_age>=35
AND gender_search IN(0,1)
AND id NOT IN (11111111,2222222)
AND (birth_year BETWEEN 1961 AND 1999)
AND (latitude BETWEEN -25.14 AND -16.13)
AND (longitude BETWEEN -54.87 AND -45.86)
ORDER BY unix_timestamp_online DESC
LIMIT 20