Mysql-重用计算所得的值,例如st_distance_sphere值

问题描述 投票:0回答:1

我的mysql(v8.0.19)测试表具有1000个位置条目。如果查询“给我所有半径500米以内的所有用户ID”,我将得到250个结果。

我的第一个查询(0.033秒)仅返回userId:

SELECT db_user_id 
FROM db.location 
where st_distance_sphere(ST_GeomFromText('POINT(51.1065133 11.1245543)', 4326), geo) <= 500;

我的第二个查询(0.045秒)返回userId和距离:

SELECT db_user_id,st_distance_sphere(ST_GeomFromText('POINT(51.1065133 11.1245543)', 4326), geo) 
FROM db.location 
where st_distance_sphere(ST_GeomFromText('POINT(51.1065133 11.1245543)', 4326), geo) <= 500;

我的猜测(为什么第二个查询要慢一些:在where语句(用于1000个位置条目)中计算st_distance_sphere,并在大约250个条目的结果中再次计算。

我的问题:有没有一种方法可以将已经计算的st_distance_sphere用作查询结果?是否有与第一个查询一样快但返回userId和distance的查询?

mysql query-optimization query-performance
1个回答
0
投票

两个查询都必须运行WHERE 1000次。

通过使其更复杂,将第二个查询缩减为仅1000个评估:

SELECT  user_id, dist
    FROM  
        ( SELECT  db_user_id,
                  st_distance_sphere(ST_GeomFromText(
                        'POINT(51.1065133 11.1245543)', 4326), geo
                           ) AS dist
              FROM  db.location 
        ) AS x
    WHERE  dist <= 500;

如果您的列表将显着增长,请参阅我对进一步优化的讨论:http://mysql.rjweb.org/doc.php/find_nearest_in_mysql

© www.soinside.com 2019 - 2024. All rights reserved.