求一个单表的SQL语句
有表4个字段
id(主键) uid mydatetime amount
现在要找出uid=5的mydatetime最大的那条记录,表的记录比较多,求最高效写法。非高效写法也没有写出来
我的尝试:
select id,uid,max(mydatetime),amount from table1 where uid=5 group by id,uid,amount;
结果是多条记录
请帮助
要只是用一次就不用管高不高效了:
-
SQL code
select * from table1 where uid=5 order by mydatetime desc limit 1
高效的做法就是uid上必须有索引
select a.id,a.uid,a.mydatetime,a.amount from test15 a inner join
(select uid,max(mydatetime) tm from test15 where uid=5) b
on a.uid=b.uid and a.mydatetime=b.tm where a.uid=5
如果为了提高效率,则需要创建 (uid,mydatetime)的索引。