Mysql 选择一列上排序下的上一行满足某些条件的行

Mysql 选择一列上排序下的上一行满足某些条件的行,mysql,sql,select,join,Mysql,Sql,Select,Join,我想知道有多少次用户打开我们的电子邮件,但一周内没有打开我们的任何电子邮件。这个查询看起来像 select * from user_email_tracking uet1 where opened_timestamp is not null and select(max(opened_timestamp) from user_email_tracking where user_id = uet1.user_id and opened_timestamp < uet1.ope

我想知道有多少次用户打开我们的电子邮件,但一周内没有打开我们的任何电子邮件。这个查询看起来像

select * from user_email_tracking uet1 where opened_timestamp is not null and
    select(max(opened_timestamp) from user_email_tracking where user_id = uet1.user_id
    and opened_timestamp < uet1.opened_timestamp
select*from user_email_tracking uet1,其中opened_时间戳不为空,并且
从用户\u电子邮件\u跟踪中选择(最大(打开的\u时间戳),其中用户\u id=uet1.user\u id
和打开的\u时间戳

即使我计算出嵌套的select out,也可能效率太低。这是一个相当大的表。我现在处理的逻辑可能不够好,因为我需要处理一个实际的完全笛卡尔连接,在我关心的字段创建的对角线下方。

您要找的是一个相关子查询,例如:

select *
from user_email_tracking uet
where opened_timestamp is not null and
      not exists (select 1
                  from user_email_tracking uet2
                  where uet2.user_id = uet.user_id and
                        uet2.opened_timestamp >= date_add(uet1.opened_timestamp, interval -7 day)
                 );
我假设
timestamp
是一个
datetime
,以便进行日期运算


为了获得最佳性能,您需要在
user\u email\u tracking(user\u id,user\u email\u tracking)

上建立一个索引。好吧,“一个解决方案是一个相关子查询”…例如上面我在相关步骤中取消的索引,但它的效率不够。