我有3个表,如下所示。在给定特定的成员名称搜索术语的情况下,我想获得成员名称,ID的列表以及每个成员的最新活动时间。
这个'最新活动时间'是比较game_record和eating_record表的最新时间。
下面给出了所需的输出。
member_info表:
name m_id
---- ----
john 1
doe 2
johnson 3
game_record:
time_of_activity game_id m_id
---------------- ------- -----
2013-01-20 23:01:00 1 3
2013-01-20 23:01:07 4 1
2013-01-20 23:01:06 1 2
2013-01-20 23:01:05 3 1
eating_record:
time_of_activity food_id m_id
---------------- ------- -----
2013-01-20 23:01:04 1 1
2013-01-20 23:01:03 4 1
2013-01-20 23:01:02 1 2
2013-01-20 23:01:01 3 3
搜索词为'john'时所需的输出:
name m_id latest_time
---- ---- -----------
john 1 2013-01-20 23:01:07
johnson 3 2013-01-20 23:01:01
到目前为止我尝试过:
我可以通过以下查询获得前2列:
select name,
m_id
from
member_info
where
name like "john%";
我可以通过以下查询获取给定成员的latest_time,但我不确定如何将第二个查询与第一个查询合并以获得我想要的输出。
select greatest ((select
max(time_of_activity)
from
game_record
join
member_info on game_record.m_id = member_info.m_id
where member_info.name = "john"),
(select
max(time_of_activity)
from
eating_record
join
member_info on eating_record.m_id = member_info.m_id
where member_info.name = "john"));
SQL小提琴可在以下位置获得:http://sqlfiddle.com/#!2/b70d0/3
P.S。表game_record和eating_record有其他专门用于游戏/食物的列,这里没有包含,因为我想简化并隔离我需要帮助的部分。
谢谢! :)
答案 0 :(得分:1)
您可以使用UNION ALL
查询在同一列中获取eating_record
和game_record
次,然后应用聚合函数获取max
时间:
select m.name,
m.m_id,
max(time_of_activity) latest_time
from member_info m
left join
(
select time_of_activity, m_id
from game_record
union all
select time_of_activity, m_id
from eating_record
) g
on m.m_id = g.m_id
where m.name like 'john%'
group by m.name, m.m_id
这也可以用子查询中的聚合编写:
select m.name,
m.m_id,
max(time_of_activity) latest_time
from member_info m
left join
(
select max(time_of_activity) time_of_activity, m_id
from game_record
group by m_id
union all
select max(time_of_activity) time_of_activity, m_id
from eating_record
group by m_id
) g
on m.m_id = g.m_id
where m.name like 'john%'
group by m.name, m.m_id;
答案 1 :(得分:0)
我的解决方案是按成员ID汇总每个表(游戏和吃饭)以获取最新时间。然后,将它们连接在一起并使用greatest()
函数获取最新时间:
select mi.*, greatest(gr.maxtime, er.maxtime) as latest_time
from member_info mi left outer join
(select m_id, MAX(time_of_activity) as maxtime
from game_record gr
group by m_id
) gr
on gr.m_id = mi.m_id left outer join
(select m_id, MAX(time_of_activity) as maxtime
from eating_record er
group by m_id
) er
on er.m_id = mi.m_id