如何计算 mysql 中的日期和当前日期之间的差异

How do you calculate the difference between the date and current date in mysql

我有一个名为“testing_tables”的 table,假设当前日期是 2022-03-01,1 个月 = 30 天。

ip founded pid
192.168.1.1 2022-01-1 1111
192.168.1.2 2022-01-1 2222
192.168.1.3 2022-01-1 3333
192.168.1.1 2022-02-1 1111
192.168.1.2 2022-02-1 2222
192.168.1.3 2022-02-1 3333
192.168.1.1 2022-03-1 1111
192.168.1.2 2022-03-1 2222
192.168.1.4 2022-03-1 4444

我正在努力实现以下结果:

ip founded pid aging_days
192.168.1.1 2022-01-1 1111 90 days
192.168.1.2 2022-01-1 2222 90 days
192.168.1.3 2022-01-1 3333 60 days
192.168.1.4 2022-03-1 4444 0 days

基本上,我想尝试计算第一个IP创建的天数,然后自动计算天数。然后仅显示 1 个 IP 和 pid,并具有以下老化天数。 Mysql 版本:8.0+

新说明:如果IP 192.168.1.3在3月份没有显示,我还有一些逻辑问题,天数仍然继续,只需要显示60天如下table

试试这个

SELECT 
    ip, MIN(founded) founded, pid, DATEDIFF(CURRENT_TIMESTAMP(), MIN(founded)) aging_days
FROM testing_tables
GROUP BY ip, pid
select ip, min(founded) as founded, pid, DATEDIFF(CURRENT_DATE,min(founded)) as aging_days 
from testing_tables
group by pid
order by pid;

您可以尝试以下方法:

SELECT ip, MIN(founded) AS founded, pid, DATEDIFF(CURRENT_TIMESTAMP(), MIN(founded)) AS aging_days FROM testing_tables GROUP BY ip, pid ORDER BY ip