简体   繁体   English

SQL查询显示添加到表中的最新数据

[英]SQL QUERY Displaying latest data added to the table

I have a SQL query that displays the latest data that was recently added into the database. 我有一个SQL查询,显示最近添加到数据库中的最新数据。 This is the query : 这是查询:

SELECT Name, Picture, briefDescription from table order by DatePosted desc limit 1

My problem is, the data that was given to me was not the latest data in the database, it gave me an old entry instead. 我的问题是,提供给我的数据不是数据库中的最新数据,而是给了我一个旧条目。 My DataPosted format is of DateTime and in the database, it is of type String. 我的DataPosted格式为DateTime,在数据库中为String类型。 Any ideas why? 有什么想法吗? Thanks in advance! 提前致谢!

If DatePosted is of type string in the database, then it will sort alphabetically, and not by date. 如果DatePosted在数据库中为字符串类型,则它将按字母顺序而不是按日期排序。 Change the DatePosted field to type DATETIME (or equivalent) in the database, and your code should work. 将DatePosted字段更改为在数据库中键入DATETIME(或等效值),您的代码应该可以工作。

For example, here is a set of sample data selected using a string DatePosted field. 例如,这是使用字符串DatePosted字段选择的一组样本数据。 As you can see, it is not sorting descendingly. 如您所见,它不是按降序排列。

SELECT * FROM TestTable ORDER BY DatePosted DESC

Id  Name    DatePosted
3   Charlie 10/12/2013 10:03:56 PM
2   Bravo   10/11/2013 9:03:56 PM
6   Delta   10/11/2013 9:03:56 AM
1   Alpha   10/11/2013 10:03:56 PM

You will most likely need to write a script to convert the data from string to DATETIME, as most DBMSs (perhaps all) will not allow you to convert a string column type to a numeric type such as DATETIME implicitly. 您很可能需要编写一个脚本来将数据从字符串转换为DATETIME,因为大多数DBMS(也许全部)都不允许您将字符串列类型隐式转换为数字类型,例如DATETIME。 You can perform this conversion in a number of ways. 您可以通过多种方式执行此转换。 Perhaps the easiest way would be to add a new column of type DATETIME, copy the data from the string column to the new DATETIME column, remove the string column, and change the name of the new column to DatePosted. 也许最简单的方法是添加类型为DATETIME的新列,将数据从字符串列复制到新的DATETIME列,删除字符串列,然后将新列的名称更改为DatePosted。

Here's an example that will perform this conversion: 这是将执行此转换的示例:

UPDATE TestTable SET DatePosted2 = CAST(DatePosted AS DATETIME)

And the new results: 和新结果:

SELECT * FROM TestTable ORDER BY DatePosted DESC

Id  Name    DatePosted
3   Charlie 2013-10-12 22:03:56.000
1   Alpha   2013-10-11 22:03:56.000
2   Bravo   2013-10-11 21:03:56.000
6   Delta   2013-10-11 09:03:56.000

instead of changing value in your database you can just cast the date in your SQL statement for the correct order: 无需更改数据库中的值,只需将SQL语句中的日期强制转换为正确的顺序即可:

SELECT Name, Picture, briefDescription 
FROM table 
ORDER BY CAST(DatePosted AS DATETIME) desc limit 1

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

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