2015-12-10 24 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')