一、substring函數
此函數可以用在HQL語句的columns部分和where後面,主要目的可以對數據庫字段中的某數據進行按條件截取,並動態組合成自已想要的數據格式,具體使用方法如:
example: oldSid:812108M00003 -> newSid:08-M00003
hql = "select substring(oldSid,5, 2)+'-'+substring(oldSid,7,6) as newSid from Table";
substring()函數一般帶有三個參數,第一個為要格式化的源字段,第二個為開始執行的起始位置,(下標從臺開始),第三個參數為從開始位置起要截取幾位數據,所有上面語句的結果為:
newSid:08-M00003
另substring函數也可以用在where語句後面如:
hql = "from Table a where substring(a.description, 1, 3) = 'cat'";
二、子查詢的用法
假設現在有兩張表Company(公司表),Employee(員工表),關係一個公司有多個員工,所以一個company記錄應該對應多條employee紀錄.即在employee有一個 FK 指向Company的 PK.
condition:找出每一個公司中員工工資(pay)最高的那一位.
hql:
select (select max(e.pay) from c.Employee e) from Company c
note:select後面的子查詢必須寫在()中,
其運行後對應的sql語句為:
select
(select
max(e.pay)
from
Employee e
where
e.HSUID=c.HSUID) as col_0_0_
from
Company c;
hql中的子查詢也可以帶查詢條件如下面也可以寫成:
select (select max(e.pay) from a.employee e where e.name=:name) from company a
select
(select
max(e.pay)
from
Employee e
where
e.HSUID=c.HSUID and e.name = '01') as col_0_0_
from
Company c;
三、coalesce函数的用法
COALESCE
返回其参数中第一个非空表达式。
语法
COALESCE (expression [ ,...n ])
参数
expression
任何类型的表达式。
n
表示可以指定多个表达式的占位符。所有表达式必须是相同类型,或者可以隐性转换为相同的类型。
返回类型
将相同的值作为 expression 返回。
注释
如果所有自变量均为 NULL,则 COALESCE 返回 NULL 值。
COALESCE(expression1,...n) 与此 CASE 函数等价:
CASE
WHEN (expression1 IS NOT NULL) THEN expression1
...
WHEN (expressionN IS NOT NULL) THEN expressionN
ELSE NULL
示例:表score代表某同学本次考试各科成绩的得分.结构如下:
語文 數學 英語
58 NULL 95
95 NULL 0
NULL NULL 34
NULL NULL NULL
0 95 NULL
0 0 0
NULL 95 95
95 NULL NULL
hql:
select a from score a where coalesce(a.chinese,a.math,a.english) = 95;
執行後結果為:
95 NULL 0
NULL 95 95
95 NULL NULL
(3 rows affected)
第一行因為a.chinese(語文)不空,所以where a.chinese = 95;return false;
第三行因為a.english = 34,所以return false;
第五行因為a.chinese = 0;標誌也不為空,所以return false;
1.elements:此函数返回所有对象集合
例如: select elements(blog.Comments) from Blog blog 返回全部blog对象的全部Comment
2.size:此函数计算集合的长度
例如: from Cat cat where size(cat.kittens) > 0
3.maxindex函数得到集合的最大索引数
例如:from Cat cat where maxindex(cat.kittens) >1000
当cat对象中kittens集合的最大索引大于1000时,,,返回cat
4.maxelement函数得到集合的值
例如:from Cat cat where maxelement(cat.kittens) >1000
当cat对象中kittens集合中的最大值大于1000 时,,,返回cat
5.index函数
例如:from Cat cat where index(cat.kittens) >12
当cat对象中kittens集合中的索引大于12时,,,返回cat

926

被折叠的 条评论
为什么被折叠?



