0

我有以下查询,它为我提供了一个始终使用最新条目作为参考的条目列表。(MAX(id)) .. 但是 max(id) 并不总是最新的条目..

那么是否有可能获得具有最新日期的条目的ID(表有一个unixtime日期字段)

当前查询

SELECT tr.id,user.ispro as ispro, user.id as user_id,tr.balance_e, user.paypal FROM tr
RIGHT join user on tr.user_id=user.id
INNER JOIN (SELECT MAX(id) as maxid FROM tr where tr.status='ok'
GROUP BY tr.user_id order by tr.date desc) la 
ON la.maxid = tr.id
WHERE tr.status='ok' and tr.balance_e >= ".$mincredit." 
ORDER BY tr.balance_e desc;

每次更新条目(日期)时,输出都不正确,因为 INNER JOIN 使用 MAX(id) ...知道如何将其更改为始终具有日期字段为最新的条目的 id 吗?

4

1 回答 1

1

试试这个:

SELECT 
  tr.id, 
  user.ispro as ispro, 
  user.id as user_id,
  tr.balance_e,
  user.paypal 
FROM tr
INNER JOIN 
(
   SELECT user_id, MAX(date) as maxdate
   FROM tr 
   where tr.status='ok'
   GROUP BY tr.user_id
) la ON tr.user_id = la.user_id AND tr.date = la.maxdate
RIGHT join user on tr.user_id=user.id 
WHERE tr.status     = 'ok'
  and tr.balance_e >= ".$mincredit." 
ORDER BY tr.balance_e desc;
于 2013-06-03T14:55:11.020 回答