MySQL 5.6 - select 结果,其中多个日期时间列中最近的至少 1 个月前
MySQL 5.6 - select results where the most recent of multiple datetime columns is 1 month ago at least
我在 mySQL 5.6 数据库中有一个包含多个日期时间列的 table。
email_id
email_sent_date (datetime)
email_replied_date (datetime)
email_bounced_date(datetime)
email_archived (datetime)
我想检索 群组的最新日期时间 的所有电子邮件(email_sent_date、email_replied_date、email_bounced_date、email_archived) 从今天开始至少是 1 个月前。
我想做这样的事情,尽管我认为我不能使用这个 max(),但你会了解我正在努力实现的目标:
SELECT *
FROM table
WHERE MAX(email_sent_date,email_replied_date, email_bounced_date, email_archived) <= CURDATE() - INTERVAL 30 DAY
如何实现?
您想要函数 greatest()
,而不是 max()
:
SELECT *
FROM table
WHERE GREATEST(email_sent_date, email_replied_date, email_bounced_date, email_archive) <= CURDATE() - INTERVAL 30 DAY;
注意:如果任何值是 NULL
,则该行将被过滤掉。
我更喜欢明确的比较,因为我认为逻辑更容易理解:
SELECT *
FROM table
WHERE email_sent_date <= CURDATE() - INTERVAL 30 DAY AND
email_replied_date <= CURDATE() - INTERVAL 30 DAY AND
email_bounced_date <= CURDATE() - INTERVAL 30 DAY AND
email_archive <= CURDATE() - INTERVAL 30 DAY;
编辑:
处理 NULL
值需要显式检查。也许:
SELECT *
FROM table
WHERE (email_sent_date <= CURDATE() - INTERVAL 30 DAY OR email_sent_date IS NULL) AND
(email_replied_date <= CURDATE() - INTERVAL 30 DAY OR email_replied_date IS NULL) AND
(email_bounced_date <= CURDATE() - INTERVAL 30 DAY OR email_bounced_date IS NULL) AND
(email_archive <= CURDATE() - INTERVAL 30 DAY OR email_archive IS NULL);
我在 mySQL 5.6 数据库中有一个包含多个日期时间列的 table。
email_id
email_sent_date (datetime)
email_replied_date (datetime)
email_bounced_date(datetime)
email_archived (datetime)
我想检索 群组的最新日期时间 的所有电子邮件(email_sent_date、email_replied_date、email_bounced_date、email_archived) 从今天开始至少是 1 个月前。
我想做这样的事情,尽管我认为我不能使用这个 max(),但你会了解我正在努力实现的目标:
SELECT *
FROM table
WHERE MAX(email_sent_date,email_replied_date, email_bounced_date, email_archived) <= CURDATE() - INTERVAL 30 DAY
如何实现?
您想要函数 greatest()
,而不是 max()
:
SELECT *
FROM table
WHERE GREATEST(email_sent_date, email_replied_date, email_bounced_date, email_archive) <= CURDATE() - INTERVAL 30 DAY;
注意:如果任何值是 NULL
,则该行将被过滤掉。
我更喜欢明确的比较,因为我认为逻辑更容易理解:
SELECT *
FROM table
WHERE email_sent_date <= CURDATE() - INTERVAL 30 DAY AND
email_replied_date <= CURDATE() - INTERVAL 30 DAY AND
email_bounced_date <= CURDATE() - INTERVAL 30 DAY AND
email_archive <= CURDATE() - INTERVAL 30 DAY;
编辑:
处理 NULL
值需要显式检查。也许:
SELECT *
FROM table
WHERE (email_sent_date <= CURDATE() - INTERVAL 30 DAY OR email_sent_date IS NULL) AND
(email_replied_date <= CURDATE() - INTERVAL 30 DAY OR email_replied_date IS NULL) AND
(email_bounced_date <= CURDATE() - INTERVAL 30 DAY OR email_bounced_date IS NULL) AND
(email_archive <= CURDATE() - INTERVAL 30 DAY OR email_archive IS NULL);