MySQL 的Where IN、Distinct 和Limit

标签 mysql

SELECT id, server_id, start_time, end_time 
FROM errors 
WHERE server_id in (3, 12, 24, 25, 26, 27, 28, 29, 30) 
ORDER BY id DESC 
LIMIT 9

这是我尝试运行并给出结果的查询,其中 server_id = 3, 12, 24, 25, 26, 27, 28, 29, 30.相反,我收到的是 server_id = 25, 25, 12, 25, 27, 27, 28, 28, 27。请注意重复的 server_ids。该查询为我提供了唯一的 id 但重复的 server_id

有没有一种方法可以获得显示每个 server_id 的最后一个 id 的结果?

我尝试过执行 ORDER BY server_id 但这给了我同样的问题。

我尝试运行DISTINCT,但这也不起作用。

最佳答案

您必须使用一些聚合函数。

类似的东西

select 
  server_id,
  max(id),
  avg(start_time),--for example
  avg(end_time)--for example
from errors
where server_id in (3, 12, 24, 25, 26, 27, 28, 29, 30) 
group by server_id
order by id desc

如果您需要与 server_id 的最大 id 相对应的 start_time 和 end_time,您可以这样做

select e.id, e.server_id, e.start_time, e.end_time
from errors e
join (select server_id, max(id) maxid
      from errors
      group by server_id) t
  on t.maxid = e.id and e.server_id = t.server_id
where e.server_id in (3, 12, 24, 25, 26, 27, 28, 29, 30) 
order by e.id DESC

关于MySQL 的Where IN、Distinct 和Limit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24679574/

相关文章:

mysql - 在 Mysql 存储过程中检索年份

php - 循环数组,如果键值存在,则向结构化数组添加 1

mysql - 如何使用 Mysql 按特定顺序从两个不同的表中选择消息?

php - 没有从 Symfony2 中的实体获取数据

mysql - Rails 3.2 解释了导致文档上传出现奇怪问题的原因

python - 为封装的 MySQL 提供密码

mysql - 将此 SQL 查询作为 Elequent 语句的最佳方法是什么

MYSQL AND 运算符在同一列中的比较

MySQL 显示任何行上没有值的列

mysql - Rails where 查询 has_and_belongs_to_many