简体   繁体   English

如何在mysql中获取最大字段的对应ID

[英]How to get the corresponding id of a max field in mysql

I am still new to mysql commands and I learned how to get the max value of a column and count of a column. 我还是mysql命令的新手,我学习了如何获取列的最大值和列数。 My database is named db and my table (named "foo") looks like this: 我的数据库名为db,我的表(名为“ foo”)如下所示:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(64) | NO   | PRI | NULL    |       |
| expires  | datetime    | YES  | MUL | NULL    |       |
| extra    | text        | YES  |     | NULL    |       |
| valid    | tinyint(1)  | NO   |     | NULL    |       |
| trust_id | varchar(64) | YES  | MUL | NULL    |       |
| user_id  | varchar(64) | YES  | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+

Basically, I want to know if there is a way to get the max date of the expires field and then print out the corresponding fields like user_id and id. 基本上,我想知道是否有一种方法可以获取到期字段的最大日期,然后打印出相应的字段,例如user_id和id。 So far this is the command I currently use to get the max date from expires in the command line 到目前为止,这是我目前用于从命令行获取最大日期的命令

mysql -u root db -e "select max(id) from foo;"

this alone will give me: 仅此一项就可以给我:

+---------------------+
| max(expires)        |
+---------------------+
| 2016-08-05 17:54:44 |
+---------------------+

What I would like to do is get this back: 我想做的就是找回这个:

+---------------------+--------+--------+
| max(expires)        | id     | user_id|
+---------------------+--------+--------+
| 2016-08-05 17:54:44 |cd97eb4 | 2bf2cec|
+---------------------+--------+--------+ 

So then I would have the max expiration date along with the id and user id for that expiration date. 因此,我将获得最大到期日期以及该到期日期的ID和用户ID。

Any insight is greatly appreciated! 非常感谢任何见识!

If you just want the id and user_id corresponding to that (max) date, then something like this should do 如果您只想要与该(最大)日期相对应的iduser_id ,则应执行以下操作

select expires, id, user_id
from foo
where expires in
    (select max(expires) 
     from foo)

Use order by and limit : 使用order by limit

select f.*
from foo f
order by f.expires desc
limit 1;

I think this is the simplest way. 我认为这是最简单的方法。 And with an index on foo(expires) , it should have the best performance as well. 并且使用foo(expires)的索引,它也应该具有最佳性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM