【问题标题】:SQLite: How to get absolute row numberSQLite:如何获取绝对行号
【发布时间】:2015-12-08 23:29:48
【问题描述】:

我试图在查询返回后获取行的绝对记录号(在 Perl 中)。假设我按如下方式查询我的表:

my $stmt = "SELECT * FROM MAIN WHERE item='widget' LIMIT 1;";
my $sth  = $dbh->prepare( $stmt );
my $rv   = $sth->execute();

如何找出返回行的绝对行号?我尝试使用 ROWID:

my $stmt = "SELECT ROWID, * FROM MAIN WHERE item='widget' ORDER BY ROWID LIMIT 1;";
my $sth  = $dbh->prepare( $stmt );
my $rv   = $sth->execute();
my $row  = $sth->fetchrow_hashref();

if( defined( $row ) ) {
  $RecordNumber = $row->{'rowid'};
}

如果您从不从表中删除一行,则此方法有效。

但行 ID 永远不会改变。所以如果你从表中删除行,rowids 不再匹配表中的绝对行号。

我希望我的问题很清楚(英语不是我的母语)。

【问题讨论】:

  • 是的,我看到了这些答案,但我对 SQLite 的了解太有限,无法理解为什么这实际上是我的问题的答案。我会再看一遍。谢谢!
  • “绝对行号”是什么意思?您只想要从1..n 订购的结果集?你想做什么?
  • 我正在尝试为 SQLite 数据库创建一个旧的 dBase 样式接口。在 dBase 中,每条记录都有一个记录号。第一条记录是记录#1,第二条记录是#2,以此类推。如果你删除了第二条记录,原来的记录#3 变成了记录#2。记录#4 变成了#3,以此类推。如果您进行了定位,它将返回此记录号。记录号是记录在数据库中的绝对位置。它不是一些唯一的 ID,因为它随着数据库的变化而变化。我正在尝试模仿这种行为。所以如果我做一个查询,我想知道返回的行在表中的位置是什么。

标签: perl sqlite


【解决方案1】:

我们来看这个例子

sqlite> create table my_example (field1);
sqlite> insert into my_example values ('abc');
sqlite> insert into my_example values ('booooo');
sqlite> insert into my_example values ('3231-556');
sqlite> .mode column
sqlite> .header on
sqlite> select * from my_example;
field1
----------
abc
booooo
3231-556
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
1           abc
2           booooo
3           3231-556
sqlite> delete from my_example where field1='abc';
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
2           booooo
3           3231-556
sqlite> insert into my_example values ('abc');
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
2           booooo
3           3231-556
4           abc
sqlite>

获得我理解你想要实现的目标(类似于 rown_num)的方法是:

sqlite> select (select count(*) from my_example b where a.rowid >= b.oid ) as cnt, * from my_example a;
cnt         field1
----------  ----------
1           booooo
2           3231-556
3           abc
sqlite>

希望对你有帮助

【讨论】:

  • @Zippy1970 oid 是 rowid 的别名。
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多