【问题标题】:How to select latest Row from table without using ORDER BY如何在不使用 ORDER BY 的情况下从表中选择最新行
【发布时间】:2013-05-29 04:24:56
【问题描述】:

如何从表格中选择最新的行而不进行排序?

这是因为它后面跟着 ID AUTO INCREMENT...

我正在使用 c# asp.net 来选择...我确实尝试使用 LIMIT 5 但它给了我一个错误页面..

rSQL = "select COUNT(*) from chatLog_db where sessionid='" + grpID + "' LIMIT 5";

有没有更好的办法解决这个问题?

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • 请定义“最新行”以及为什么不能使用 ORDER BY
  • 我只想显示 sessionID 中最新的 5 行,而不是自动递增
  • 亲爱的看到我更新的答案并检查第二个查询,这将解决您的问题。

标签: asp.net sql-server sql-server-2008 c#-4.0 code-behind


【解决方案1】:

您有一个自动递增的 id 列,对吗?那你就可以这样了。。

select * from tablename where id=(select MAX(rid) from tablename)

【讨论】:

  • 但是如何只显示5个或更少?
  • 尝试 select * from tablename order by columnname desc LIMIT 5;
  • 或 SELECT TOP 10 * FROM custdetails1 ORDER BY customerid DESC
【解决方案2】:

在 MSSQL 上,只需使用 top 1 而不是限制

select top(1) * from mytable order by some_column

http://msdn.microsoft.com/en-us/library/ms189463.aspx

【讨论】:

    【解决方案3】:

    如果最新的意思是最大的id

       select * from chatLog_db 
       where id = (select max(id) from chatLog_db);
    

    编辑

    选择 5 条记录

       select * from chatLog_db 
       where id > (select max(id) - 5 from chatLog_db);
    

    【讨论】:

    • 但是如何只显示5个或更少?
    【解决方案4】:

    你可以试试

    SELECT * FROM chatLog_db WHERE sessionid > (SELECT MAX(sessionid) - 1 FROM chatLog_db);
    

    你也可以试试

    SELECT * FROM chatLog_db WHERE sessionid > (SELECT MAX(sessionid) - 5 FROM chatLog_db);
    

    您也可以使用max 以及喜欢

    select * from chatLog_db where sessionid = (select max(sessionid) from chatLog_db);
    

    类似的东西。

    如果您没有在查询中使用order by,因为您认为它会改变您的 dsplay 数据的顺序,那么我会告诉您,sort 您的数据也有一个技巧,可以根据您的需要

    即使您正在使用,您也可以根据需要对数据进行排序 order by 进入您的查询,将结果放入 DataView 并对其进行排序 根据您的需要,因为 DataView 允许我们将排序设施作为 好吧。

    最新使用Order By点赞

    select * from tablename order by columnname desc LIMIT 5;
    

    希望它对你有用。

    【讨论】:

    • 我会试试...非常感谢
    • 但是如何只显示5个或更少?
    • 在你的问题中你提到How to select latest Row from table without using ORDER BY 而现在你想要to display only 5 or less...
    • 因为我想从最新的...不便
    • 如果你想显示数据那么为什么你在查询中使用count(*)。它只是给你integer值而不是data
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多