【发布时间】:2020-05-15 12:52:18
【问题描述】:
所以当我添加ORDER BY date_last_access DESC 时遇到问题,整个查询会减慢到 3 秒,没有它大约是 0.2 秒,为什么它运行这么慢,我该如何更改查询以更快地运行?
所有使用的表和字段也有索引。
用户:1+ 百万条记录 点赞数:5+ 百万条记录(超过 10 亿条生产量)
一旦投入生产,表格将增长得非常快。
查询
SELECT
id,
sid,
first_name,
date_birth,
location,
date_created,
date_last_access,
(3956 * 2 * ASIN(
SQRT(
POWER(
SIN(
({LAT} - latitude) * pi() / 180 / 2
),
2
) + COS({LAT} * pi() / 180) * COS(latitude * pi() / 180) * POWER(
SIN(
({LON} - longitude) * pi() / 180 / 2
),
2
)
)
)) AS distance
FROM
users
WHERE
`id` != {UID} AND
`gender` = {GEND} AND
`date_birth` BETWEEN {DOB_MIN} AND {DOB_MAX} AND
`status` = 'active' AND
(SELECT COUNT(*) FROM likes WHERE likes.judged_user = users.id AND likes.user_id = {UID}) = 0
HAVING distance <= {DIST}
ORDER BY date_last_access DESC
LIMIT {ROWS}
解释
1 PRIMARY users ref PRIMARY,Index_2,discovery,index_1 index_1 2 const 226184 Using index condition; Using where; Using filesort
2 DEPENDENT SUBQUERY likes eq_ref PRIMARY,index_1,index_2 PRIMARY 16 const,hello.users.id 1 Using index
索引
喜欢 - user_id, judged_user - 正常 - BTREE
用户 - id、gender、date_birth、status、date_last_access - 正常 - BTREE
当我通过id 而不是date_last_access 订购时,它似乎运行得更快,可能是因为 date_last_access 是datetime 格式吗?
【问题讨论】:
-
你有
date_last_access的索引吗? -
所有使用的表和字段也有索引:请告诉我们您在
users表上有哪些索引。 -
@Nick - 我愿意
-
建议编辑您的问题以包含更多信息。