0

我只想删除以下语句返回的行,我该怎么做?

  select usersernum,username,useremail 
    from core.appuser
   where usersernum in (
              select ch.usersernum
                from core.appusersession ch
               where ch.usersernum not in (
                          select usersernum
                            from (
                                       select max(starttime) as maxstarttime
                                            , usersernum
                                         from core.appusersession  vip
                                        where vip.starttime >= '2011-01-01 00:00:00'
                                     group by usersernum
                                 )
                     )
            group by usersernum
         )
order by useremail
       ;
4

3 回答 3

1

你可以使用

DELETE  FROM core.appuser WHERE usersnum IN (
     select  usersernum 
       from  core.appuser
      where  usersernum in (
             select  ch.usersernum
               from  core.appusersession ch
              where  ch.usersernum not in (
                 select  usersernum from (
                     select  max(starttime) as maxstarttime, usersernum
                       from  core.appusersession  vip where vip.starttime>='2011-01-01 00:00:00' group by usersernum))
          group by  usersernum)
    order by  useremail);
于 2013-08-08T23:44:15.353 回答
0

您没有说您正在运行什么平台或版本的 DB2,但如果您使用的是 DB2 9.7 for Linux、UNIX 和 Windows 或更高版本,您可以使用超级方便的“delete from select”:

delete from (
  select usersernum,username,useremail 
    from core.appuser
   where usersernum in (
              select ch.usersernum
                from core.appusersession ch
               where ch.usersernum not in (
                          select usersernum
                            from (
                                       select max(starttime) as maxstarttime
                                            , usersernum
                                         from core.appusersession  vip
                                        where vip.starttime >= '2011-01-01 00:00:00'
                                     group by usersernum
                                 )
                     )
            group by usersernum
         )
    order by useremail
);
于 2013-08-09T06:29:08.850 回答
0

有时退一步问问自己,这里的真正目标是什么,用“业务术语”或日常用语而不是 SQL 是有帮助的。

您的查询看起来有一堆不必要的层。看来您真正想要做的是删除所有非活动用户,即自 2011 年初以来尚未开始会话的用户。

DELETE  FROM core.appuser 
  WHERE usersernum NOT IN 
    ( SELECT DISTINCT usersernum
        FROM core.appusersession  
        WHERE starttime>='2011-01-01 00:00:00'
    );

是不是简单多了?

于 2013-08-09T22:51:01.087 回答