为了提高效率,我们不需要将所有的数据捞出来判断,只需要判断是否存在就可以了,即true or false的问题
1采用EXISTS语句(resultType=“java.lang.Integer”,返回0/1)
例1:
单表
查询是否存在时间大于’2021-03-05’的且money大于0的数据,如果存在(可能有多条,包括只有1条)返回int类型,1;如果不存在,则返回0
select exists (SELECT *
from a
where
money>0 and time>'2021-03-05';
如图说明此条件下存在数据:(具体几条不知道,至少一条)
例2
多表:
要查询a,b表中xId相关联,且筛选(例如传入)的某个唯一字段Code和时间为条件,查询money或总数大于0的数据是否存在,同样返回0/1
select exists (SELECT *
from a join b
on a.xId=b.xId
and a.code=1 and b.time>'2021-03-05'
where
b.money>0 or b.amount>0);
2,采用limit 1(返回1/null)
例如:
上面例1
SELECT 1 as isExist
from a
where money>0
and time>'2020-03-05'
limit 1;
limit 1的作用便是提高效率,只需要查询一条而不是所有,但是如果有(1或1+)则返回1,如果没有则返回null
**再如例2:**用此写法为:
SELECT 1 as isExist(列名)
from a join b
on a.xId=b.xId
and a.code=1 and b.time>'2021-03-05'
where
b.money>0 or b.amount>0
limit 1;
如图结果为此条件下不存在: