1. 程式人生 > >mybatis一對多及分頁可能存在的問題即關聯查詢分頁問題,巢狀的list中數量對不上

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