简体   繁体   English

如何在SQL中选择表的最后一条记录?

[英]How to select the last record of a table in SQL?

This is a sample code to select all records from a table.这是从表中选择所有记录的示例代码。 Can someone show me how to select the last record of that table?有人可以告诉我如何选择该表的最后一条记录吗?

select * from table

When I use: SELECT * FROM TABLE ORDER BY ID DESC LIMIT I get this error: Line 1: Incorrect syntax near 'LIMIT'.当我使用: SELECT * FROM TABLE ORDER BY ID DESC LIMIT我收到此错误:第 1 行:'LIMIT' 附近的语法不正确。 This is the code I use:这是我使用的代码:

private void LastRecord()
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HELPDESK_OUTLOOKConnectionString3"].ToString());

    conn.Open();
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("SELECT * FROM HD_AANVRAGEN ORDER BY " +
                "aanvraag_id DESC LIMIT 1", conn);
    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    {
        TextBox1.Text = (myReader["aanvraag_id"].ToString());
        TextBox1.Text += (myReader["wijziging_nummer"].ToString());
        TextBox1.Text += (myReader["melding_id"].ToString());
        TextBox1.Text += (myReader["aanvraag_titel"].ToString());
        TextBox1.Text += (myReader["aanvraag_omschrijving"].ToString());
        TextBox1.Text += (myReader["doorlooptijd_id"].ToString());
        TextBox1.Text += (myReader["rapporteren"].ToString());
        TextBox1.Text += (myReader["werknemer_id"].ToString());
        TextBox1.Text += (myReader["outlook_id"].ToString());
    }
}

Without any further information, which Database etc the best we can do is something like没有任何进一步的信息,我们可以做的最好的数据库等就像

Sql Server数据库服务器

SELECT TOP 1 * FROM Table ORDER BY ID DESC

MySql数据库

SELECT * FROM Table ORDER BY ID DESC LIMIT 1

to get the last row of a SQL-Database use this sql string:要获取SQL 数据库的最后一行,请使用以下 sql 字符串:

SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);

Output:输出:

Last Line of your db!你数据库的最后一行!

Assuming you have an Id column:假设您有一个 Id 列:

SELECT TOP 1 *
  FROM table
 ORDER
    BY Id DESC;

Also, this will work on SQL Server.此外,这将适用于 SQL Server。 I think that MySQL you might need to use:我认为您可能需要使用 MySQL:

SELECT *
  FROM table
 ORDER
    BY Id DESC
 LIMIT 1

But, I'm not 100% sure about this.但是,我不是 100% 确定这一点。

EDIT编辑

Looking at the other answers, I'm now 100% confident that I'm correct with the MySQL statement :o)查看其他答案,我现在 100% 确信我对 MySQL 语句是正确的:o)

EDIT编辑

Just seen your latest comment.刚看到你的最新评论。 You could do:你可以这样做:

SELECT MAX(Id)
  FROM table

This will get you the highest Id number.这将为您提供最高的 ID 号。

SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1

是的,这是 mysql,SQL Server:

SELECT TOP 1 * FROM Table ORDER BY ID DESC
SELECT * FROM TABLE WHERE id = (SELECT MAX(id) FROM TABLE);

SELECT MAX(id)表示获取表中最大的id它返回一个数字,这是现在使用WHERE id = maxId的最大ID你可以获得id最大的行,这意味着你使用的最后一行自动递增。

SELECT * FROM table ORDER BY Id DESC LIMIT 1

It is always a good practice in your table design to have an automatic row identifier, such as在您的表设计中使用自动行标识符始终是一个好习惯,例如

 [RowID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL

, then you can identify your last row by ,然后您可以通过以下方式识别您的最后一行

 select * from yourTable where rowID =  @@IDENTITY 

MS SQL Server has supported ANSI SQL FETCH FIRST for many years now: MS SQL Server 多年来一直支持 ANSI SQL FETCH FIRST

SELECT * FROM TABLE
ORDER BY ID DESC 
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY

(Works with most modern databases.) (适用于大多数现代数据库。)

如果您有一个自增字段(比如ID ),那么您可以执行以下操作: SELECT * FROM foo WHERE ID = (SELECT max(ID) FROM foo)

当您颠倒顺序时,最后一个只是第一个。

Almost all answers assume the ID column is ordered (and perhaps auto incremented).几乎所有的答案都假设 ID 列是有序的(并且可能是自动递增的)。 There are situations, however, when the ID column is not ordered, hence the ORDER BY statement makes no sense.但是,在某些情况下,ID 列排序,因此 ORDER BY 语句没有意义。

The last inserted ID might not always be the highest ID, it is just the last (unique) entry.最后插入的 ID 可能并不总是最高的 ID,它只是最后一个(唯一的)条目。

One possible solution for such a situation is to create a row id on the fly:对于这种情况,一种可能的解决方案是动态创建行 ID:

SET @r = 0;
SELECT * FROM (SELECT *, (@r := @r + 1) AS r_id FROM my_table) AS tmp
    ORDER BY r_id DESC LIMIT 1;

In Oracle, you can do:在 Oracle 中,您可以执行以下操作:

SELECT *
FROM (SELECT EMP.*,ROWNUM FROM EMP ORDER BY ROWNUM DESC)
WHERE ROWNUM=1;

This is one of the possible ways.这是可能的方法之一。

select ADU.itemid, ADU.startdate, internalcostprice 
from ADUITEMINTERNALCOSTPRICE ADU

right join

   (select max(STARTDATE) as Max_date, itemid 
   from ADUITEMINTERNALCOSTPRICE
   group by itemid) as A

on A.ITEMID = ADU.ITEMID
and startdate= Max_date

I think this should do it.我认为应该这样做。

declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;

If your table has no auto incremented value and otherwise has no good element to order on, you can get the arbitrary order of the items in any collection like this如果您的表没有自动递增的值,否则没有好的元素可以排序,您可以像这样获得任何集合中项目的任意顺序

SELECT
    [item]
FROM (
    SELECT
        *
        , ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY GETDATE()) 'RN'
    FROM [TABLE]
) RDR 
WHERE [RN] = (
    SELECT
        MAX([RN])
    FROM (
        SELECT
            *
            , ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY GETDATE()) 'RN'
        FROM [TABLE]
    ) RDR 
)

An important caveat is that the performance for this is going to be abysmal with larger sets of data.一个重要的警告是,对于更大的数据集,其性能将非常糟糕。

$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

你也可以做这样的事情:

SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;

I upvoted Ricardo.我赞成里卡多。 Actually max is much efficient than sorting .实际上 max 比 sort 有效得多。 See the differences.查看差异。 its excellent.它的优秀。

I had to get the last row/update record (timeStamp)我必须得到最后一行/更新记录(时间戳)

`sqlite> select timeStamp from mypadatav2 order by timeStamp desc limit 1;
 2020-03-11 23:55:00
 Run Time: real 1.806 user 1.689242 sys 0.117062`

`sqlite> select max(timeStamp) from mypadatav2;
 2020-03-11 23:55:00
 Run Time: real 0.553 user 0.412618 sys 0.134340`

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

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