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
。
我是否有办法获得可以显示每个id
的最后server_id
的结果?
我尝试过做ORDER BY server_id
,但这给了我同样的问题。
我试过运行DISTINCT
,但这也行不通。
答案 0 :(得分:1)
您遇到的问题是每个服务器只需要一条记录,其中包含最大ID ..和相关信息。您需要将结果限制为最大ID ...这是单向...
SELECT id, server_id, start_time, end_time
FROM errors
WHERE server_id in (3, 12, 24, 25, 26, 27, 28, 29, 30)
and ID = (Select max(ID) from errors E2 where E2.server_ID=errors.server_ID)
ORDER BY id DESC
LIMIT 9
答案 1 :(得分:1)
你必须使用一些聚合函数。
像
这样的东西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对应于max 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