![](/img/trans.png)
[英]For a specific user_id get the latest rows (time-wise) that this user is in with all other users, in MySQL
[英]get latest points for all users
我正在獲取最新的時間戳記,但是分數比較舊。我正在尋找具有最新分數的最新時間戳記作為響應,並且每個接收者只能獲取最后一個。 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;
嘗試類似:
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
選擇每條記錄的最大日期來首先選擇所需的行(子查詢)。 接下來,您可以將這些記錄與原始表連接起來以獲取分數。
這是一般的想法。 您可以計算出細節
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
您看到的地方在任何地方都必須相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.