简体   繁体   English

如何从数据库中选择倒数第二行和最后一行?

[英]How can I select the second last and last row from the database?

When we are retrieving data from database, we use something like this当我们从数据库中检索数据时,我们使用这样的东西

SELECT * FROM Names

However, we will get all the data inside the specific table.但是,我们将获取特定表中的所有数据。 Since I am going to update some data to the database and want to make a comparison bewteen the last row of data in the db and the most updated data, how can I select and retrieve the last two row of the database only?由于我要向数据库更新一些数据,并且想在数据库中的最后一行数据和最新更新的数据之间进行比较,如何仅选择和检索数据库的最后两行?

SQL Server syntax: SQL Server 语法:

SELECT TOP 2 column_name FROM table_name ORDER BY column_name DESC;  

Example:例子:

If you want to retrieve the last value of the customer_name column from the customers table, you need to write the following query:如果要从customers表中检索customer_name列的最后一个值,则需要编写以下查询:

SELECT LAST (CUSTOMER_NAME) AS LAST_CUSTOMER FROM CUSTOMERS;  

如果您使用的是 SQL Server,您将执行以下操作:

SELECT TOP 2 * FROM Names ORDER BY Name DESC

You should include a column in the Names table to keep track of when a name was added to the table since you cannot guarantee that the rows are in the order that they were inserted.您应该在 Names 表中包含一列以跟踪名称何时添加到表中,因为您不能保证行按它们插入的顺序排列。 With that column you can use the order by clause..使用该列,您可以使用 order by 子句..

In MySQL Syntax:在 MySQL 语法中:

SELECT *
FROM Names
ORDER BY order_column DESC
LIMIT 2;

If you want to get the last rows as they are, you cannot order the table by the inserted names because that is just getting the 2 names that come last in an alphabetically sorted list of names.如果您想按原样获取最后一行,则不能按插入的名称对表进行排序,因为这只是获取按字母顺序排序的名称列表中最后的 2 个名称。 You could try something like this where you include an offset in the limit clause if you get the number of rows in the table:如果您获得表中的行数,您可以尝试这样的事情,其中​​您在限制子句中包含一个偏移量:

SELECT *
FROM Names
LIMIT *num_rows*-2, 2;

You would have to know the number of rows to use this query or use an additional query to implement a row count that works with limit.您必须知道行数才能使用此查询或使用附加查询来实现与限制一起使用的行数。 This, however, still may not be accurate since the system may not order the rows as they were inserted.但是,这仍然可能不准确,因为系统可能不会在行插入时对其进行排序。 I still recommend the first option where you keep track of order/time a name was inserted.我仍然推荐第一个选项,您可以跟踪插入名称的顺序/时间。

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

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