引用子查询的where子句中的列

时间:2015-01-18 17:23:23

标签: mysql sql left-join where-clause

我有一个包含多个会话事件记录的表。每行是会话中的事件,会话可以具有同一事件的倍数。这些基本上是游戏会话,每个事件都是圆形开始或圆形结束。我的数据看起来像

Session_id | Event_type | Event_Time
1 | round_start | 12:01:00
1 | round_end | 12:02:00
1 | round_start| 12:05:00
1 | round_end | 12:7:00
2 | round_start | 14:11:00
2 | round_end | 14:12:00
3 | round_start| 15:09:00
3 | round_end | 15:13:00

我试图找到平均轮次。我尝试了以下SQL

select
RS.session_id,
RS.Event_Time as StartTime,
RE.EndTime,
TIMESTAMPDIFF(MINUTE,RE.EndTime,RS.Event_Time) as duration
from amp_event_mamlaka as RS
left join 
(
    select session_id, min(event_time) as EndTimd from amp_event_mamlaka 
    where Event_Type = "Round End" and session_id = RS.session_id and  event_time>RS.Event_Time
) RE
on RE.session_id = RS.session_id

问题是我无法在连接表中引用RS.session_id和RS.event_time。

我正在使用MySQL。有关如何实现这一目标的任何建议吗?

由于

3 个答案:

答案 0 :(得分:2)

我建议您使用相关子查询来处理此问题:

select RS.session_id, RS.Event_Time as StartTime,
       (select smin(event_time) 
        from amp_event_mamlaka em
        where em.session_id = RS.session_id and
              em.Event_Type = 'Round End' and 
              em.event_time > RS.Event_Time
       ) as EndTime,
from amp_event_mamlaka RS;

您可以使用子查询来执行时间戳差异:

select RS.*, TIMESTAMPDIFF(MINUTE, EndTime, Event_Time) as duration
from (select RS.session_id, RS.Event_Time as StartTime,
             (select min(event_time) 
              from amp_event_mamlaka em
              where em.session_id = RS.session_id and
                    em.Event_Type = 'Round End' and 
                    em.event_time > RS.Event_Time
             ) as EndTime
      from amp_event_mamlaka RS
     ) RS

答案 1 :(得分:1)

您可以将条件保留在Join where子句中,而不是将其保留在subquery的{​​{1}}子句中。试试这个。

On

答案 2 :(得分:1)

与嵌套查询相反,子查询应该只返回一个值。您的需求是您需要来自成对行的数据的示例。子查询仅用于连接对,而不是用于提供数据。 Fiddle

select  e1.SessionID, e1.EventType, e1.EventTime, e2.EventType, e2.EventTime, TimeStampDiff( minute, e1.EventTime, e2.EventTime ) Duration
from    Events  e1
join    Events e2
    on  e2.SessionID    = e1.SessionID
    and e2.EventType    = 'end'
    and e2.EventTime    =(
        select  Min( EventTime )
        from    Events
        where   SessionID   = e1.SessionID
            and EventType   = 'end'
            and EventTime   > e1.EventTime )
where   e1.EventType = 'start';