cont
表包含许多具有相同userid
的记录。我试图从 dist
列中为每个唯一的用户 ID 选择最小距离值。
SELECT sec.*, r.contid, r.lng, r.lat, **math formula for distance** < $withinMiles AS dist
FROM cont r
JOIN s_cont s
ON r.userid = s.userid
WHERE (( **math formula for distance**))
ORDER BY dist ASC
最佳答案
您需要使用带有having子句的分组:
SELECT sec.*, r.contid, r.lng, r.lat, MIN(**math formula for distance**) AS dist
FROM cont r
JOIN s_cont s
ON r.userid = s.userid
GROUP BY r.userid
HAVING MIN(**math formula for distance**) < $withinMiles
ORDER BY dist ASC
GROUP BY 会将具有相同用户 ID 的行分组在一起,MIN() 将从这些行中提取最小值(即具有相同用户 ID 的行)。 HAVING 的工作方式与 WHERE 类似,但基于已聚合的值。
关于mysql - 根据列的最小值选择记录,但保留其他约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19545786/