我有一个游戏服务器,我想得到一个最被忽视的玩家账户列表。
我有一个用户表
Table1 - Users:
Name | ID | otherstuff
Troll | 1 | .
CoolGuy | 2 | .
我有一个忽略表
Table2 - Ignores
id_UserWhoIsIgnoring | id_UserWhoIsIgnored
2 | 1
3 | 1
现在这一切都很棒,我可以这样做:
select
u.name,
ig.id_UserWhoIsIgnored,
count(ig.id_UserWhoIsIgnored) as ignoreCount
from ignores ig
inner join users u
on ig.id_UserWhoIsIgnored = u.id
group by id_UserWhoIsIgnored
order by ignoreCount desc
limit 25;
但问题在于,我得到了很长时间内无法连接的用户的帐户。我想将查询限制为过去30天内连接的用户。我有第三张桌子sessions
Table3 - Sessions
id_user | start_time | otherstuff
1 | 2014-06-25 00:00:00 | .
(id)OldTroll | 2010-01-01 00:00:00 | .
如何组合我的第一个查询给出列表,但仅限于where start_time > date_sub(now(), interval 45 days)
为我提供id的结果。在这种情况下,我不希望显示OldTroll
的行,即使他们最被忽略,因为他们最近的连接已有数年之久。
答案 0 :(得分:1)
如果start_time
表中有users
,那么只需使用where
:
select u.name, ig.id_UserWhoIsIgnored, count(ig.id_UserWhoIsIgnored) as ignoreCount
from ignores ig inner join
users u
on ig.id_UserWhoIsIgnored = u.id
where start_time > date_sub(now(), interval 45 days)
group by id_UserWhoIsIgnored
order by ignoreCount desc
limit 25;
如果start_time
表中有ignores
,那么只需使用having
:
select u.name, ig.id_UserWhoIsIgnored, count(ig.id_UserWhoIsIgnored) as ignoreCount
from ignores ig inner join
users u
on ig.id_UserWhoIsIgnored = u.id
group by id_UserWhoIsIgnored
having max(start_time) > date_sub(now(), interval 45 days)
order by ignoreCount desc
limit 25;
编辑:
然后我猜你想要:
select u.name, ig.id_UserWhoIsIgnored, count(ig.id_UserWhoIsIgnored) as ignoreCount
from ignores ig inner join
users u
on ig.id_UserWhoIsIgnored = u.id inner join
(select id_user, max(start_time) as start_time
from sessions
group by id_user
) s
on u.id_user = s.id_user and
s.start_time >= date_sub(now(), interval 45 days)
group by id_UserWhoIsIgnored
order by ignoreCount desc
limit 25;