mybatis一对多及分页可能存在的问题即关联查询分页问题,嵌套的list中数量对不上

项目中遇到了一个小问题,在此记录下,方便以后代码复用并且能快速排查这个小问题。

需求如下:评论和回复是一对多的关系,并且根据评论进行分页查询,至于回复数量不做限制,有多少就查多少。

存在问题:由于两张表是用连接查询,所以对于同一条评论存在多条回复的情况,那么用sql查询出来的数量应该是由回复数量决定的。而映射到java集中的数量却是由评论来决定,多条回复只是作为评论的一个属性而已。所以在mysql中直接使用limit可能会造成sql和java两边的数据不一致。

其中的column是sql中查询字段,property是javaBean属性字段。replyList就是评论中回复列表字段,是一个集合。

亲测子查询有效

select column_name,(select count(distinct ticket.id) from mac_ticket ticket where ticket.ticket_type_cd=mtt.code)totalTicket,(select count (case when ticket.customer_cd is not null or ticket.out_customer_cd is not null then ticket.id end)from mac_ticket ticket where ticket.ticket_type_cd=mtt.code)receiveSum,(select count (case when ticket.activity_id is not null  then ticket.id end)from mac_ticket ticket where ticket.ticket_type_cd=mtt.code)publishSum,(select count (case when ticket.verification=1  then ticket.id end)from mac_ticket ticket where ticket.ticket_type_cd=mtt.code)receiveSum,(select ifnull (sum(ifnull(mtg.quantity,0)),0)from mac_ticket_group mtg where mtg.ticket_type_cd=mtt.code)preLockSum from  mac_ticket_type mtt left mac_ticket_type_service  mtts on mtt.code=mtts.ticket_type_cd where mtt.delete_flag=0 <include refid="findBySelective"/>

<if test="pageBean != null and pageBean.offset != null">

and mtt.code in(select temp.code from (

select code from mac_ticket_type mtt where mtt.delete_flag=0

<include refid="findBySelective"/>

limit #{pageBean.offset},#{pageBean.size} )

as temp)

</if>

总结:

1. in不能和limit在一个语句中使用,否则报错

This version of Mysql dose't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'应加临时表查询;

2. 临时表查询时和主查询的条件要一样,,否则查询出数据不对;

3. 条件中有foreach的item的名称不要和collection的名称一样,否则报错:

Error evaluating expression 'orgCds'.Return value was ont iterable.

<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">

#{id,jdbcType=VARCHAR}

</foreach>

4.统计数时候count是单个的,可以在结果部分select count(*)from table,这样会很慢

5.ifnull可以去掉查出来的结果为null

猜你喜欢

转载自blog.csdn.net/qq_34412985/article/details/85106648
今日推荐