2014-06-30 22 views
0

双连接我有一个游戏服务器,并且我想获得最忽略的玩家帐户的列表。如果第三个表中的行匹配条款

我有一个用户表

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的行,即使它们最容易被忽略,因为它们最近的连接已经过去了几年。

回答

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; 
+0

即使我在所有3个表中都有数据,我仍然从运行中返回空集。会话子查询自身返回行,就像我原来的用户/忽略连接示例一样。我不知道如何在这里继续。 – Daenyth

+0

@Daenyth。 。 。也许没有人在过去的45天内被忽视。 –

+0

@Daenyth。 。 。删除'start_time'上的条件,并将'max(s.start_time)'放在外部'select'中。 –

相关问题