查询¶
查询是 QL 程序的输出。它们求值为结果集。
- 查询有两种类型。对于给定的 查询模块,该模块中的查询是
我们通常也把整个 QL 程序称为查询。
select 子句¶
编写查询模块时,您可以包含一个 **select 子句**(通常位于文件末尾),其格式如下
from /* ... variable declarations ... */
where /* ... logical formula ... */
select /* ... expressions ... */
“from
” 和 “where
” 部分是可选的。
- 除了 “表达式” 中描述的表达式之外,您还可以包含
- “
as
” 关键字,后跟一个名称。这为结果列提供了一个“标签”,使您可以在随后的 select 表达式中使用它们。 - “
order by
” 关键字,后跟结果列的名称,以及可选的 “asc
” 或 “desc
” 关键字。这决定了显示结果的顺序。
- “
例如
from int x, int y
where x = 3 and y in [0 .. 2]
select x, y, x * y as product, "product: " + product
此 select 子句返回以下结果
x | y | product | |
---|---|---|---|
3 | 0 | 0 | product: 0 |
3 | 1 | 3 | product: 3 |
3 | 2 | 6 | product: 6 |
您也可以在 select 子句末尾添加 “order by y desc
”。现在,结果将根据 “y
” 列中的值降序排列
x | y | product | |
---|---|---|---|
3 | 2 | 6 | product: 6 |
3 | 1 | 3 | product: 3 |
3 | 0 | 0 | product: 0 |
查询谓词¶
查询谓词是一个带有 “query
” 注释的 非成员谓词。它返回谓词求值的所有元组。
例如
query int getProduct(int x, int y) {
x = 3 and
y in [0 .. 2] and
result = x * y
}
此谓词返回以下结果
x | y | result |
---|---|---|
3 | 0 | 0 |
3 | 1 | 3 |
3 | 2 | 6 |
编写查询谓词而不是 select 子句的一个好处是,您可以在代码的其他部分调用该谓词。例如,您可以在 类 的主体中调用 “getProduct
”。
class MultipleOfThree extends int {
MultipleOfThree() { this = getProduct(_, _) }
}
相比之下,select 子句就像一个匿名谓词,因此您无法在以后调用它。
在调试代码时,将 “query
” 注释添加到谓词中也可能会有所帮助。这样,您可以明确地查看谓词求值的元组集。