我在这里有这么大的查询:
select
user_contact_id as userContactId,
max(attempt_number) as attemptNumber,
max(sent_timestamp) as sentTimestamp,
source as source,
from
share_email_tracking `set`
group by
user_contact_id
having
(attemptNumber = 1 and date_sub(CURDATE(), interval 4 day) >= date(sentTimestamp))
问题是,我实际上对attemptNumber
或sentTimestamp
不感兴趣。我只需要那些来计算“having”子句。我不知道有任何语法可以做到这一点,我认为这是一个比“拥有”更普遍的问题所以我无法在文档中找到它。我相信临时变量是可能的,但据我所知,这些是特定于会话的,而不是特定于查询的,我不希望它们污染状态。这可能吗?
在现实生活中,我多次复制sentTimestamp
所以我应该避免将其替换为原始版本。
答案 0 :(得分:2)
您可以将它们放在Having
中。只需使用实际表达式而不是别名。
select user_contact_id as userContactId,
source as source
from share_email_tracking `set`
group by user_contact_id
having (max(attempt_number) = 1 and date_sub(CURDATE(), interval 4 day) >= max(sent_timestamp))
如果您想要别名表达式,则可以执行此操作,这样您就不必在having子句中多次写入它们。创建一个子选择,然后使用主查询的WHERE
子句中的别名。
select userContactId, source
FROM
(
select user_contact_id as userContactId,
max(attempt_number) as attemptNumber,
max(sent_timestamp) as sentTimestamp,
source as source
from share_email_tracking `set`
group by user_contact_id
) as x
WHERE (attemptNumber = 1 and date_sub(CURDATE(), interval 4 day) >= date(sentTimestamp))
答案 1 :(得分:0)
你可以在where子句
中完成它们 select
user_contact_id as userContactId,
max(attempt_number) as attemptNumber,
max(sent_timestamp) as sentTimestamp,
source as source,
from
share_email_tracking `set`
group by
user_contact_id
HAVING max(attempt_number) = 1 AND date(sentTimestamp) <= date_sub(CURDATE(), interval 4 day)