2015-12-10 23 views
0

我執行這兩個表聯接在MySQL選擇唯一不同的行基於最高時間戳上加入

挑戰表

challenge_ID(int) |to_user(int)|from_user(int)|timestamp 

用戶表

iduser(int)|email(string) 

我加入查詢此:

Select distinct u.email,c.challenge_id,c.status,c.timestamp from 
test.challenges c join test.users u 
on 
    c.to_user=u.iduser 
where 
    c.from_user=9 and (c.status='open' || c.status='rejected') 
Order by 
    c.timestamp DESC 

結果我從這個查詢得到的是

email   |challenge_id| status |timestamp (Descending) 
[email protected]  5   open  2015-12-09 21:20:26 
[email protected] 4   open  2015-12-09 21:10:22 
[email protected]  1   rejected 2015-12-08 12:27:00 

通知[email protected]如何重複兩次,我希望它只是一次顯示和顯示的應該有最新的時間戳即

email   |challenge_id| status |timestamp (Descending) 
    [email protected]  5   open  2015-12-09 21:20:26 
    [email protected] 4   open  2015-12-09 21:10:22 

回答

0

你應該寫你的查詢爲:

Select u.email, c.challenge_id, c.status, c.timestamp 
from test.challenges c join 
    test.users u 
    on c.to_user = u.iduser 
where c.from_user = 9 and c.status in ('open', 'rejected') 
Order by c.timestamp DESC; 

,除非必要,不要使用select distinct。然後你可以用各種方法做你想做的事。因爲你有一個join和其他條件,我認爲變量可能是最簡單的方法:

select cu.* 
from (Select u.email, c.challenge_id, c.status, c.timestamp, 
      (@rn := if(@e = u.email, @rn + 1, 
         if(@e := u.email, 1, 1) 
         ) 
      ) as rn 
     from test.challenges c join 
      test.users u 
      on c.to_user = u.iduser cross join 
      (select @e := '', @rn := 0) params 
     where c.from_user = 9 and c.status in ('open', 'rejected') 
     order by u.email, c.timestamp DESC 
    ) cu 
where rn = 1; 

編輯:

我想用join和在單個查詢相應的變量上面。但是,有時MySQL的迷糊,你需要使用帶有變量的子查詢:

select cu.* 
from (select cu.*, 
      (@rn := if(@e = u.email, @rn + 1, 
         if(@e := u.email, 1, 1) 
         ) 
      ) as rn 
     from (Select u.email, c.challenge_id, c.status, c.timestamp, 
      from test.challenges c join 
       test.users u 
       on c.to_user = u.iduser 
      where c.from_user = 9 and c.status in ('open', 'rejected') 
      order by u.email, c.timestamp DESC 
      ) cu cross join 
      (select @e := '', @rn := 0) params 
    ) cu 
where rn = 1; 
+0

我以前從來沒有使用可變的,我想了解你給 我跑在我的數據庫查詢,似乎它返回相同的(組電子郵件ID壽),但RN遺體1表示所有行,並返回所有3行s – Snedden27

+0

我發現這很難遵循,因爲我不使用mysql(或RDs)來處理其他基本查詢。我複製粘貼這在我的phpadmin,它給了我一個語法錯誤附近的第一次加入 我想出了一個查詢連接使用子查詢,我已經發布在答案。我沒有太多的測試,但顯然它服務於目的 請讓我知道,如果這不是最有效的方式做到這一點 – Snedden27

0

我想出一個查詢,這裏面的作品,不知道它的萬無一失,最有效的方式做到這一點

這裏這是壽

 Select distinct u.email,c.challenge_id,c.status,c.timestamp 
      from 
       (select ch.challenge_id,ch.status,ch.from_user,ch.to_user,timestamp, 
        (select Max(timestamp) from challenges 
         where to_user=ch.to_user 
         and from_user=9 
        ) as latest 
       from test.challenges ch 
       )c 
      join test.users u 
      on 
       c.to_user=u.iduser 
      and 
      c.latest=c.timestamp 
    where (c.status='open' || c.status='rejected')