使用记录 ID

Ninox 中的记录 ID

  • Ninox 中的每条新记录都会被分配一个唯一的 ID(标识符)。
  • 对于新建的表,编号从 1 开始,每新增一条记录就递增 1(2、3 等)。
  • 已删除的 ID 不会被重新分配。因此,表中最大的 ID 反映的是已创建记录的总数,其中包括那些已被删除、不再可见的记录。
  • ID 的表示形式:
    • ID 可以表示为数字,也可以表示为文本。
    • 表示为文本时,ID 由表的 ID(一个或多个大写字母)与记录编号组合而成。
      例如:"A1"

关于 ID 的要点

  • 把 ID 转换为文本:
    • 使用 string() 函数可获得 ID 的文本表示。
    • text() 函数只会把 ID 的数字部分作为文本返回。例如:"1"。
  • 示例:
Ninox
"Correct textual representation, e.g. ""A1""";
string(maTable.id);
"Only the numeric part as text, e.g. ""1""";
text(maTable.id);
  • 在表达式中使用 ID:
    • 进行算术运算或字符串拼接时,ID 会采用另一侧数据的类型。
  • 示例:
Ninox
var t := "Num ID: " + maTable.id;

输出:Num ID: 1

按 ID 查找记录

要在 where 子句中按 ID 取回一条记录,您可以使用数字,也可以使用文本表示。

使用数字:

Ninox
select Customer where id = 1;

使用文本:

使用文本时,请确保 ID 同时包含表的 ID 和记录编号。

例如:

Ninox
select Customer where id = "B1";

从 ID 中提取记录编号

这个函数可以从基于文本的 ID(例如 A1)中提取出记录编号:

Ninox
function recordNumber(id : text) do
  "Capture the digit group.";
  number(extractx(id, "^[A-Z]+([0-9]+)$", "", "$1"))
end;

"Example: apply to the current record’s ID";
var numId := recordNumber(string(myId));

string(myId) 把 ID 转换为文本。

正则表达式 ^[A-Z]+([0-9]+)$ 的含义是

  • ^[A-Z]+ → 开头的一个或多个字母,
  • ([0-9]+) → 我们需要的数字(捕获组 1),
  • $ → 字符串结尾。

extractx(..., "", "$1") 只返回捕获到的数字。

number(...) 把该数字字符串转换成数字。

用 record() 查找记录

record(Table, n) 直接返回编号为 n 的记录,无需遍历整张表。编号必须是大于零的整数:

  • 小数(3.5)、零或负数都不返回任何内容,也没有任何提示:Ninox 不会对编号四舍五入;
  • 3.0 可以接受:它等于 3;
  • 文本("3")或列表([3, 4])在编写公式时就会被拒绝(“Expression does not return a number”、“Expression returns multiple values”):以文本形式收到的编号须先用 number() 转换。

这个陷阱常见于计算得出的编号(record(Customer, total / 2),当 total 为奇数时),或从外部收到的编号,例如通过 API。

Ninox
"Found: record number 3";
record(Customer, 3);
"Nothing, and no error: Ninox does not round";
record(Customer, 3.5);
"A number received as text must be converted first";
record(Customer, number("3"));

注意

与任何记录都不对应的整数(已删除或尚未创建)并不会返回“空”:record() 返回的是指向一条不存在的记录的引用。因此 if record(Customer, 999999) then 为真,而 if record(Customer, 3.5) then 为假。

要判断记录是否存在,请检查它的 ID:在这两种情况下它都是空的。

Ninox
var n := 3.5;
if record(Customer, n).id then
  "The record exists"
else
  "No record: n is not a whole number greater than zero, or no record has this number"
end

(通过 API 在一张 8 条记录的表上实测。)