ITEEDU

10.4. select子句

select子句选择在结果集中返回哪些对象和属性。思考一下下面的例子:

select mate 
from eg.Cat as cat 
    inner join cat.mate as mate

这个查询会选择出作为其它猫(Cat)朋友(mate)的那些猫。当然,你可以更加直接的写成下面的形式:

select cat.mate from eg.Cat cat

你甚至可以选择集合元素,使用特殊的elements功能。下面的查询返回所有猫的小猫。

select elements(cat.kittens) from eg.Cat cat

查询可以返回任何值类型的属性,包括组件类型的属性:

select cat.name from eg.DomesticCat cat
where cat.name like 'fri%'

select cust.name.firstName from Customer as cust

查询可以用元素类型是Object[]的一个数组返回多个对象和/或多个属性。

select mother, offspr, mate.name 
from eg.DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr

或者实际上是类型安全的Java对象

select new Family(mother, mate, offspr)
from eg.DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

上面的代码假定Family有一个合适的构造函数。

10.5. 统计函数(Aggregate functions)

查询可以返回属性的统计函数。

select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
from eg.Cat cat

在select子句中,统计函数的变量也可以是集合。

select cat, count( elements(cat.kittens) ) 
from eg.Cat cat group by cat

下面是支持的统计函数列表:

  • avg(...), sum(...), min(...), max(...)

  • count(*)

  • count(...), count(distinct ...), count(all...)

distinct 和 all关键字的用法和语义与SQL相同。

select distinct cat.name from eg.Cat cat

select count(distinct cat.name), count(cat) from eg.Cat cat