mysql - 根据列的最小值选择记录,但保留其他约束

标签 mysql

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/

相关文章:

mysql - (Mysql) 按日期时间范围合并两个表

mysql - 如何让MySQL知道顺序查询引起的ID?

mysql - 如何在 2 个表上进行连接,但只返回一个表的数据?

mysql - 使用 INSERT INTO ... ON DUPLICATE KEY 时绑定(bind) MySQL 变量

php - 如何获取向服务器请求页面的客户端信息?

mysql - rails 数据库 :migrate error rails aborted

mysql - IF 条件不能正常工作

mysql - 在 UNION 之后保留 ORDER BY

MySQL 时间戳格式

mysql - 尝试使用同一表中的值更新表