总结一个常用的通知数据的sql
原型展示
这里的数据展示, 需要将数据库中的数据按照不同条件统计并返回给前端
有一下几种方案
方案 一
:
上方展示的每个数据都写一条sql, 书写简单, 但是比较费事, 重复劳动 。这里不做展示
方案 二
:
利用子查询,将多条sql写在一个大sql中, 其实本质上依然是多条sql, 而且子查询多了, 数据库查询效率也会比较慢, 这在数据量大的时候, 尤为明显, 子查询代码如下
select
(select count(cu.id) from cloud_user cu where cu.userType=3 ) as partner_count,
(select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state !=2 ) as not_car_owner_partner_count,
(select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state = 2 ) as car_owner_partner_count,
(select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state = 4 ) as stopPartnerCount
from cloud_user cu
方案 三
:
利用case when , 代码如下
<select id="getPartnerStatistics" resultType="com.etouch.pojo.dto.minipro.CloudUserDataDTO">
select
sum(case when cu.userType=3 then 1 else 0 end ) as partner_count,
sum(case when cu.userType=3 and cu.state !=2 then 1 else 0 end ) as not_car_owner_partner_count,
sum(case when cu.userType=3 and cu.state = 2 then 1 else 0 end ) as car_owner_partner_count,
sum(case when cu.userType=3 and cu.state = 4 then 1 else 0 end ) as stopPartnerCount
from cloud_user cu
where <include refid="searchCloudUserData"/>
</select>
case when 条件成立时, 会运行then 后面的, 也就是取1, 不成立则 运行 else 后面的, 取 0, 最后一定要加上end, 否则, 运行会报错