获取所有用户的最新积分

时间:2014-02-09 15:43:53

标签: mysql sql

我正在获取最新的时间戳,但是得分很高。我正在寻找最新的时间戳,最新的分数作为响应,每个接收器只有最后一个。 http://www.sqlfiddle.com/#!2/07d11/1

 CREATE TABLE if not exists tblA
    (
    id int(11) NOT NULL auto_increment ,
    sender varchar(255),
    receiver varchar(255),
     msg varchar(255),
     date timestamp,
      points varchar(255),
     PRIMARY KEY (id)
    );

    CREATE TABLE if not exists tblB
    (
    id int(11) NOT NULL auto_increment ,
    sno varchar(255),
    name varchar(255),
     PRIMARY KEY (id)
    );


    INSERT INTO tblA (sender, receiver,msg,date,points ) VALUES
    ('1', '2', 'buzz ...','2011-08-21 14:11:09','10'),
    ('1', '2', 'test ...','2011-08-21 14:12:19','20'),
    ('1', '3', 'buzz ...','2011-08-21 14:11:09','10'),
    ('1', '3', 'test ...','2011-08-21 14:12:19','20'),
    ('1', '4', 'buzz ...','2011-08-21 14:11:09','10'),
    ('1', '4', 'test ...','2011-08-21 14:12:19','20');



    INSERT INTO tblB (sno, name ) VALUES
    ('1', 'Aa'),
    ('2', 'Bb'),
    ('3', 'Cc'),
    ('4', 'Dd'),
    ('5', 'Ee'),
    ('6', 'Ff'),
    ('7', 'Gg'),
    ('8', 'Hh');

sql:

select *, max(date)
from tblA a join
     tblB b
     on b.sno in (a.receiver) 
group by b.name
order by max(date) desc;

2 个答案:

答案 0 :(得分:1)

尝试类似:

SELECT *
FROM (

  SELECT tblB.*, MAX(tblA.date) AS date
  FROM tblB
  JOIN tblA ON tblB.sno = tblA.receiver
  GROUP BY tblB.sno

) AS subset
JOIN tblA ON subset.sno = tblA.receiver 
            AND subset.date = tblA.date

我们的想法是首先选择所需的行(子查询),方法是从tblB中选择每条记录的最大日期。接下来,您可以将这些记录与原始表联系起来以获取分数。

答案 1 :(得分:0)

这是一般性的想法。你可以弄清楚细节

select field1, field2, etc
from table
join (
select id, max(timestamp) maxts
from table
where whatever
group by id ) temp on table.id = temp.id
where whatever
and timestamp = ts

无论哪个部分都必须与你看到的地方相同。