mysql更有效的查询方式

下面完成了工作,但我觉得我违反了编程规则.

select *
from serverTable
where server like ‘proc1@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc2@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc3@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘pro4@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc5@server1’
order by reg_date desc
limit 1

有没有更好的方法或正确的方法来完成这项工作?

最佳答案 一种选择是为每个服务器组找到最大reg_date,其中服务器可以从UNION查询中获取5个值中的一个,然后从表中为每个服务器组选择完整记录.

SELECT t1.*
FROM serverTable t1
INNER JOIN
(
    SELECT server,
           MAX(reg_date) AS reg_date
    FROM serverTable
    WHERE server in ('proc1@server1', 'proc2@server1', 'proc3@server1', 'proc4@server1', 'proc5@server1')
    GROUP BY server
) t2
    ON t1.server = t2.server AND
       t1.reg_date = t2.reg_date
点赞