[英]MySQL with Where IN and Distinct and Limit
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
This is the query I'm trying to run to give me results where the server_id
= 3, 12, 24, 25, 26, 27, 28, 29, 30
. 这是我试图运行给我结果的查询,其中
server_id
= 3, 12, 24, 25, 26, 27, 28, 29, 30
。 Instead, what I receive is server_id
= 25, 25, 12, 25, 27, 27, 28, 28, 27
. 相反,我收到的是
server_id
= 25, 25, 12, 25, 27, 27, 28, 28, 27
。 Note the repeating server_ids. 请注意重复的server_ids。 The query gives me unique
id
but duplicate server_id
. 该查询为我提供了唯一的
id
但有重复的server_id
。
Is there a way I can get results that would show me the last id
for each server_id
? 有没有一种方法可以让我看到每个
server_id
的最后一个id
?
I've tried doing ORDER BY server_id
but that gives me the same issue. 我已经尝试执行
ORDER BY server_id
但这给了我同样的问题。
I tried running DISTINCT
but that also does not work. 我试过运行
DISTINCT
但这也不起作用。
The issue you have is that you need only one record from each server with the max ID.. and relative information. 您遇到的问题是,每台服务器仅需要一条记录,记录中包含最大ID和相关信息。 You need to limit the results to just that max ID... Here's one way...
您需要将结果限制为最大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
you'll have to use some aggregation functions. 您将必须使用一些汇总功能。
Something like 就像是
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
if you need tht start_time and end_time corresponding to the max id by server_id, you may do 如果您需要start_time和end_time对应于server_id的最大ID,则可以这样做
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.