简体   繁体   English

如何在Android sqlite中的现有行之前插入新行?

[英]How to insert a new row before an existing row in Android sqlite?

My table is not sorted and I keep it sorted in the code logic. 我的表未排序,并且在代码逻辑中将其保持排序。

I would like to insert a new row at the beginning of the table - before any other existing row. 我想在表格的开头插入一个新行-在任何其他现有行之前。 Is there a way to do this? 有没有办法做到这一点? Thanks. 谢谢。

SQL tables do not have a defined order; SQL表没有定义的顺序。 to return rows in a specific order, you must use an ORDER BY clause. 要以特定顺序返回行, 必须使用ORDER BY子句。

In SQLite, table rows are stored in the order of their internal rowid (which is also the value of the INTEGER PRIMARY KEY column, if any). 在SQLite中,表行按其内部rowid的顺序存储(如果有的话,它也是INTEGER PRIMARY KEY列的值)。 To store a row before all other rows, insert the new row with a rowid value that is smaller than all others: 要在所有其他行之前存储一行,请插入一个rowid值小于所有其他行的新行:

INSERT INTO MyTable(rowid, Name, Comment)
VALUES ((SELECT MIN(rowid) FROM MyTable) - 1, 'me', 'first!');

(Please note that the first paragraph still applies; storage order is not guaranteed to be query order. You still need to use ORDER BY.) (请注意,第一段仍然适用;不能保证存储顺序为查询顺序。您仍然需要使用ORDER BY。)

If you want to do it regularly (like when you want to show latest content first) you can store it normally but reverse the data with query like this. 如果您想定期执行此操作(例如,当您想首先显示最新内容时),则可以正常存储它,但可以使用这样的查询来反转数据。

select * from MYTABLE ORDER BY _id DESC 

this query give you the latest row first. 该查询首先为您提供最新行。

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

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