mybatis contains one-to-many paging query problem

In business, sometimes you need to use left join to query join tables, and you need to manually perform limit paging query, but mybatis is to first paging query and then map the data structure, for example, when you need to divide 10 records into one page, the database finds 10 records As a result, there may not be 10 records returned to the front-end after the mybaits mapping result, which causes the front-end page to display abnormally. This is because mybatis helps us map the same records in the left table to the same object, while multiple records in the right table are mapped to the collection. So how can we ensure that there are 10 different records in the left table?

Method one (collection select)

The first method can use sub-query mapping, but the disadvantage is that multiple SQL statements will be generated, which will cause performance degradation
as shown in the figure below. If you find the picture on the Internet, you can select Baidu mybatis collection by yourself, mainly by specifying the subselect in the collection tag. Query, and then pass the fields in the column to the subquery to serve as the query conditions. Simply put, instead of joining the table, you check their own and then pack the results together. Although you get the desired result, the result is Every time a main query record is found, a sub-query sql statement will be generated to query the corresponding multi-party data. It can be imagined that it will affect the performance very much and is not recommended.
Insert picture description here

Method two (nested query)

Another way is to use nested queries directly in sql, like

select A.xxx, B.xxx from 
( select A.xxx, A.xxx, A.xxx from a_table A limit 0,10 ) as A 	 -- 先分好页得到结果再联表
left join b_table B on A.xx = B.xx 
left join ......

Simply put, it is to find out the 10 data of the main table to form a temporary table and then query the table with the desired table.

If there are other ways or something wrong, please correct me, learn and make progress together! ! !

Guess you like

Origin blog.csdn.net/weixin_45879810/article/details/110952655