我需要的是为每个unique player_id
获取最新的(按日期时间)table_id
表:
buyin_id player_id table_id date_time
---------|-----------|----------|--------------------|
1 | 10 | 21 | 2015-01-26 00:00:01
2 | 11 | 21 | 2015-01-26 00:00:02
3 | 12 | 21 | 2015-01-26 00:00:03
4 | 10 | 21 | 2015-01-26 00:00:04
5 | 11 | 21 | 2015-01-26 00:00:05
6 | 12 | 22 | 2015-01-26 00:00:06
7 | 13 | 22 | 2015-01-26 00:00:07
8 | 13 | 22 | 2015-01-26 00:00:08
期望的结果:
buyin_id player_id table_id date_time
---------|-----------|----------|--------------------|
3 | 12 | 21 | 2015-01-26 00:00:03
4 | 10 | 21 | 2015-01-26 00:00:04
5 | 11 | 21 | 2015-01-26 00:00:05
6 | 12 | 22 | 2015-01-26 00:00:06
8 | 13 | 22 | 2015-01-26 00:00:08
我尝试了类似这样的东西,每个table_id只返回1行而不是1行
SELECT pb.buyin_id, pb.player_id, pb.buyin, pb.cashout, pb.cashout_error, pb.date_time
FROM poker_buyin AS pb
INNER JOIN (SELECT player_id, MAX(date_time) AS MaxDateTime
FROM poker_buyin GROUP BY player_id) groupedpb
ON pb.player_id = groupedpb.player_id
AND pb.date_time = groupedpb.MaxDateTime
WHERE pb.player_id = '$player_id'";
答案 0 :(得分:0)
您提到的查询会查找每个玩家ID的最新记录。然后你过滤它只找到一个玩家,所以你得到一行。
如果你想找到每个玩家和桌子的最新记录,你的内部查询需要是:
SELECT MAX(buyin_id) buyin_id
FROM poker_buyin
GROUP BY player_id, table_id
这将从表中获取代表最新播放器/表组合的行ID。
然后你用它来从你的表中提取记录,如(http://sqlfiddle.com/#!2/be68b7/2/0)
SELECT whatever_columns
FROM poker_buyin
WHERE buyin_id IN
(
SELECT MAX(buyin_id) buyin_id
FROM poker_buyin
GROUP BY player_id, table_id
)
WHERE player_id = '$player_id'
ORDER BY player_id, table_id
此查询中有一个小技巧:buyin_id值不断上升,因此这是为每种组合选择最新时间记录的好方法。
答案 1 :(得分:0)
如果您在简单的结果列中不需要buyin_id
:
SELECT DISTINCT player_id, table_id, max(date_time) as dt
FROM `poker_buyin `
GROUP BY player_id, table_id