2014-06-30 23 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'中。 –

相關問題