8.11. サブクエリ
副選択をサポートするデータベースの場合、EJB-QL はクエリ内のサブクエリをサポートします。サブクエリはかっこ (多くの場合、SQL 集約関数コール) で囲む必要があります。相関サブクエリ (外部クエリのエイリアスを参照するサブクエリ) も許可されます。
select fatcat from Cat as fatcat
where fatcat.weight > (
select avg(cat.weight) from DomesticCat cat
)
select fatcat from Cat as fatcat
where fatcat.weight > (
select avg(cat.weight) from DomesticCat cat
)
select cat from DomesticCat as cat
where cat.name = some (
select name.nickName from Name as name
)
select cat from DomesticCat as cat
where cat.name = some (
select name.nickName from Name as name
)
select cat from Cat as cat
where not exists (
from Cat as mate where mate.mate = cat
)
select cat from Cat as cat
where not exists (
from Cat as mate where mate.mate = cat
)
select cat from DomesticCat as cat
where cat.name not in (
select name.nickName from Name as name
)
select cat from DomesticCat as cat
where cat.name not in (
select name.nickName from Name as name
)
選択リストに複数の式があるサブクエリの場合は、タプルコンストラクタを使用できます。
select cat from Cat as cat
where not ( cat.name, cat.color ) in (
select cat.name, cat.color from DomesticCat cat
)
select cat from Cat as cat
where not ( cat.name, cat.color ) in (
select cat.name, cat.color from DomesticCat cat
)
一部のデータベース (Oracle または HSQLDB ではない) では、他のコンテキスト (たとえば、コンポーネントまたは複合ユーザータイプを問い合わせる場合) でタプルコンストラクタを使用できます。
select cat from Person where name = ('Gavin', 'A', 'King')
select cat from Person where name = ('Gavin', 'A', 'King')
これはより詳細な以下のクエリと同じです。
select cat from Person where name.first = 'Gavin' and name.initial = 'A' and name.last = 'King')
select cat from Person where name.first = 'Gavin' and name.initial = 'A' and name.last = 'King')
このようなことを行いたくない 2 つの理由が考えられます。1 つはデータベースプラットフォーム間で完全に移植可能でないこと、もう 1 つはクエリがマッピングドキュメントのプロパティの順序に依存することです。