我有以下查询,它为我提供了始终使用最新条目作为引用的条目列表。 (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一 ?
最佳答案
试试这个:
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;
关于mysql - 使用 where 子句对非键列进行内连接选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899620/