MySQL选择一行,加入多个

时间:2011-05-27 17:47:42

标签: mysql join one-to-many

我有一个名为sessions的表设置如下:

#################################
# set    # timestamp  # session #
#################################
# 5      # 1306458002 # 11      #
# 3      # 1306473234 # 6       #
# 3      # 1305241207 # 3       #
...
#################################

我有一个名为events的第二个表设置如下:

#######################
# session    # code   #
#######################
# 6          # 45     #
# 6          # -10    #
# 6          # 0      #
# 3          # 7      #
...
#######################

我需要选择给定集的最新会话,然后在该一条记录之上加入相关的事件代码。最重要的是,我只需要提供一组信息(这里的设置为3):

########
# code #
########
# 45   #
# -10  #
# 0    #
########

2 个答案:

答案 0 :(得分:2)

select
    e.code
from
    (select
        max(session) as session
    from
        sessions s
    where
        s.set = 3) ms
    inner join event e on e.session = ms.session

答案 1 :(得分:0)

select e.code
from events e
inner join sessions s
    on s.session = e.session
where s.set = <whatever set you want>
and s.timestamp = (select max(timestamp) from sessions where set = s.set)