簡體   English   中英

從mysql結果獲取最新記錄

[英]get latest records from mysql result

我有我的mysql查詢,該查詢在php腳本中使用:

select distinct dhcp_logs_public.service,
dhcp_logs_public.ip,
dhcp_logs_public.date as date,
dhcp_logs_public.until as until
from dhcp_logs_public
where dhcp_logs_public.ip in('79.109.1.200','71.109.160.123','21.110.151.110')
AND dhcp_logs_public.date >= DATE_ADD(NOW(), INTERVAL -48 Hour)

這給了我這樣的結果:

service         ip                date            until
PONS1   79.109.1.200    11.10.2014 17:17    11.10.2014 19:17
PONS2   71.109.160.123  11.10.2014 19:09    12.10.2014 3:09
PONS2   71.109.160.123  11.10.2014 23:09    12.10.2014 7:09
PONS2   71.109.160.123  12.10.2014 3:09     12.10.2014 11:09
PONS3   71.109.160.123  12.10.2014 7:09     12.10.2014 15:09
PONS4   71.109.160.123  12.10.2014 16:19    12.10.2014 17:19
PONS4   71.109.160.123  12.10.2014 16:49    13.10.2014 0:49
PONS5   21.110.151.110  13.10.2014 9:22     13.10.2014 11:22
PONS5   21.110.151.110  13.10.2014 10:34    13.10.2014 12:34
PONS5   21.110.151.110  13.10.2014 11:46    13.10.2014 13:46
PONS5   21.110.151.110  13.10.2014 11:46    13.10.2014 13:46

我需要修改查詢以實現此目的:(每個IP地址的最新記錄)

service         ip                date            until
PONS1   79.109.1.200    11.10.2014 17:17    11.10.2014 19:17
PONS4   71.109.160.123  12.10.2014 16:49    13.10.2014 0:49
PONS5   21.110.151.110  13.10.2014 11:46    13.10.2014 13:46

我嘗試了類似子查詢的方法,但是我的表太大(〜10億行),無法快速處理它。 我也嘗試通過ip添加max(date)和group,但是沒有運氣。

有任何想法嗎?

您可以使用not exists來選擇所有行,其中not exists具有相同ip和較新日期的另一行(這意味着所選行是其ip地址的最新行)

select d.service,
d.ip,
d.date,
d.until
from dhcp_logs_public d
where d.ip in('79.109.1.200','71.109.160.123','21.110.151.110')
and d.date >= DATE_ADD(NOW(), INTERVAL -48 Hour)
and not exists (
    select 1 from dhcp_logs_public d2
    where d2.ip = d.ip
    and d2.date > d.date
)

該查詢可以利用(ip,date)上的復合索引

編輯

如果您可以依靠id列來確定行的最新程度,則以下內容可能會更快

select d.service,
d.ip,
d.date,
d.until
from dhcp_logs_public d
where d.ip in in('79.109.1.200','71.109.160.123','21.110.151.110')
and d.date >= DATE_ADD(NOW(), INTERVAL -48 Hour)
and d.id = (select max(id) from dhcp_logs_public d2 where d2.ip = d.ip)

或使用派生表而不是子查詢

select d.service,
d.ip,
d.date,
d.until
from dhcp_logs_public d
join (
    select max(id) max_id
    from dhcp_logs_public
    where d.ip in in('79.109.1.200','71.109.160.123','21.110.151.110')
    and d.date >= DATE_ADD(NOW(), INTERVAL -48 Hour)
    group by ip 
) t1 on t1.max_id = d.id

您確定GROUP BY無效嗎?

其他嘗試:

SELECT DISTINCT 
    MAX(dhcp_logs_public.service) as service,
    dhcp_logs_public.ip,
    MAX(dhcp_logs_public.date) as date,
    MAX(dhcp_logs_public.until) as until

    FROM dhcp_logs_public
    WHERE dhcp_logs_public.ip in('79.109.1.200','71.109.160.123','21.110.151.110')
    AND dhcp_logs_public.date >= DATE_ADD(NOW(), INTERVAL -96 Hour)
    GROUP BY dhcp_logs_public.ip

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM