简体   繁体   English

从表中仅选择日期时间值最高的一行

[英]Select only one row from table with the highest datetime value

I have a table that looks similar to this: 我有一个看起来与此类似的表:

images
    image_id       int
    user_id        int
    datetime       datetime

So, I need to get only one result. 因此,我只需要得到一个结果。 This result should have a specific user_id and should only be the most recent row in the table. 此结果应具有特定的user_id,并且应仅是表中的最新行。

I've checked out many similar questions, but wasn't able to understand how to do it and the codes I found didn't work at all. 我已经检查了许多类似的问题,但无法理解该怎么做,我发现的代码根本不起作用。

How can I achieve this? 我该如何实现?

Here's a start query: 这是一个开始查询:

SELECT *
FROM image
WHERE user_id = :user_id 

How do I change this query to select only the most recent row with a specific user_id? 如何更改此查询以仅选择具有特定user_id的最新行?

You can use order by clause like this: 您可以像这样使用order by子句:

SELECT *
FROM image
WHERE user_id = :user_id ORDER BY datetime DESC LIMIT 1

For SQL Server you can use: 对于SQL Server,您可以使用:

SELECT TOP(1) *
FROM image
WHERE user_id = :user_id 
ORDER BY datetime DESC

For MySQL try the following: 对于MySQL,请尝试以下操作:

SELECT * FROM image 选择*从图像
WHERE user_id = :user_id 在哪里user_id =:user_id
ORDER BY datetime DESC limit 1 ORDER BY日期时间DESC 限制1

limit will work with MySQL limit将适用于MySQL

For further info on MySql statements look here: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax.html 有关MySql语句的更多信息,请参见: http : //dev.mysql.com/doc/refman/5.0/en/sql-syntax.html

Select * from images where User_id = :User_id Order by datetime DESC Limit 1 从其中User_id =:User_id的图像中选择*,按日期时间DESC限制1

Hope it works :) 希望它能工作:)

通过使用限制,您可以获得所需数据的数量

limit required_no.

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

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