在MySQL中返回每个“ group by”的“ last”行

有没有更有效的方法来执行以下操作?

select * 

from foo as a

where a.id = (select max(id) from foo where uid = a.uid group by uid)

group by uid;

)

这个答案看起来很相似,但这是这样做的最好方法-

如何在MySQL中为每个组选择第一行?

谢谢,

克里斯。

PS表看起来像:

CREATE TABLE foo (

id INT(10) NOT NULL AUTO_INCREMENT,

uid INT(10) NOT NULL,

value VARCHAR(50) NOT NULL,

PRIMARY KEY (`id`),

INDEX `uid` (`uid`)

)

数据:

id, uid, value

1, 1, hello

2, 2, cheese

3, 2, pickle

4, 1, world

结果:

id, uid, value

3, 2, pickle

4, 1, world

有关更多详细信息,请参见http://www.barricane.com/2012/02/08/mysql-select-last-matching-

row.html。

回答:

试试这个查询-

SELECT t1.* FROM foo t1

JOIN (SELECT uid, MAX(id) id FROM foo GROUP BY uid) t2

ON t1.id = t2.id AND t1.uid = t2.uid;

然后使用EXPLAIN分析查询。


SELECT t1.* FROM foo t1

LEFT JOIN foo t2

ON t1.id < t2.id AND t1.uid = t2.uid

WHERE t2.id is NULL;

以上是 在MySQL中返回每个“ group by”的“ last”行 的全部内容, 来源链接: utcz.com/qa/429738.html

回到顶部