Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

mysql - Count locations withing given distance

I have the following query, that selects places withing given radius:

SELECT *
FROM (
  SELECT 
    group, 
    name,  
    111.1111 *
    DEGREES(ACOS(LEAST(1.0, COS(RADIANS(".$lat."))
       * COS(RADIANS(t1.lat))
       * COS(RADIANS(".$lon.") - RADIANS(t1.lon))
       + SIN(RADIANS(".$lat."))
       * SIN(RADIANS(t1.lat))))) AS distance
  FROM t1
) AS grp
WHERE distance < 10

Is there a way to count how many locations in each group withing this query?

question from:https://stackoverflow.com/questions/65836041/count-locations-withing-given-distance

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In MySQL you can use HAVING to reduce the number of rows.

SELECT 
    `group`, COUNT(*) NumOfNames
FROM
    (SELECT 
        `group`,
            name,
            ST_DISTANCE_SPHERE(POINT('.$lon.', '.$lat.'), POINT(t1.lon, t1.lat)) / 1000 AS distance
    FROM
        t1
    HAVING distance < 10) t2
GROUP BY `group`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...