我有以下查询,它提供了一个条目列表,总是使用最新的条目作为参考。 (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一个?
答案 0 :(得分: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;