我读了那么久以前下面的解决方案,但我不能找到链接信贷,但这里有云:
SELECT users.*, payments.method, payments.id AS payment_id, payments2.id
FROM users
JOIN payments
ON users.id = payments.user_id
LEFT JOIN payments2
ON payments.user_id = payments2.user_id
AND payments.id < payments2.id
WHERE payments2.id IS NULL
要理解它是如何工作的,只是下降的WHERE payments2.id IS NULL
,你会看看发生了什么,例如它可以产生下面的输出(我没有构建模式来测试这个,所以它是伪输出)。假设有在payments
以下记录:
id | user_id | method
1 | 1 | VISA
2 | 1 | VISA
3 | 1 | VISA
4 | 1 | VISA
和上面的SQL(不WHERE payments2.id IS NULL
条款)应出示:
users.id | payments.method | payments.id | payments2.id
1 | VISA | 1 | 2
1 | VISA | 1 | 3
1 | VISA | 1 | 4
1 | VISA | 2 | 3
1 | VISA | 2 | 4
1 | VISA | 3 | 4
1 | VISA | 4 | NULL
正如你所看到的最后一行产生期望的结果,和由于没有payments2.id > 4
,所以LEFT JOIN结果为payments2.id = NULL
。
我发现这个解决方案比我接受的答案快得多(来自我的早期测试)。
使用不同的模式,但类似的查询中,16095条记录:
select as1.*, as2.id
from allocation_status as1
left join allocation_status as2
on as1.allocation_id = as2.allocation_id
and as1.id < as2.id
where as2.id is null;
16095 rows affected, taking 4.1ms
相比MAX /子查询的接受的答案:
SELECT as1.*
FROM allocation_status as1
JOIN (
SELECT max(id) as id
FROM allocation_status
group by allocation_id
) as_max on as1.id = as_max.id
16095 rows affected, taking 14.8ms
的[我可以使用聚合函数(
可能重复最后)在MySQL ??](http://stackoverflow.com/questions/5495913/can-i-use-aggregation-function-last-in-mysql) – 2011-04-16 16:58:36
请参阅上面的答案中的答案如何从组中获取最新的记录 – 2011-04-16 17:01:06
即使使用MAX(payments.id),这也不会选择相应的值,即付款方法。如果我使用MAX(payments.id)运行查询,它将选择最近的付款ID,但是是第一种付款方式。 – Ryan 2011-04-16 17:02:22