2

我在这里有这个大查询:

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))

问题是,我实际上对attemptNumberor并不感兴趣sentTimestamp。我只需要那些来计算“有”子句。我不知道有什么语法可以做到这一点,我认为这是一个比“拥有”更普遍的问题,所以我无法在它的文档中找到它。我相信临时变量是可能的,但据我所知,这些是特定于会话的,而不是特定于查询的,我不希望它们污染状态。这可能吗?

在现实生活中,我重复了sentTimestamp好几次,所以我应该避免将它替换为生的。

4

2 回答 2

3

你可以把它们放在你的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))
于 2013-08-02T17:24:02.077 回答
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)
于 2013-08-02T17:19:59.503 回答