MySQL多表关联分页查询优化实践
发布于
# database
工作过程中遇到一个分页排序问题,具体是有一个一对多的表,需要根据后者的条件进行排序。
问题描述
原先的SQL只是简单的left join第二张表。结果会造成同一个结果在页面上展示多次,其中只有某一个字段不一样。
解决步骤
1.left join时先查出来一个子表(可能性能会差,但是我也没有好的办法),在这个子表中进行条件筛选,得到的值group by
select
case when zp.project_order_type = 0
then t1.allHour / 8 * msup.supplier_unit_price
else zp.purchase_detail_amount end as purchaseDetailAmount,
case when zd.zentao_project_id is not null then 0 else 1 end as custom_manage_status,
CASE zp.project_order_type
WHEN 0 THEN 1
WHEN 5 THEN 2
ELSE zp.project_order_type + 2
END AS custom_order_type
from
zentao_project zp
left join master_supplier msup on zp.supplier_id = msup.supplier_id
left join
(select zzdd.zentao_project_id as zentao_project_id from zentao_demand zzdd
where zzdd.data_source_type = 1 and (zzdd.manage_status is null or zzdd.manage_status = 0)
group by zzdd.zentao_project_id) zd on zp.id = zd.zentao_project_id
where
zp.data_source_type = 1
order by
custom_manage_status ASC,
custom_order_type ASC,
zp.spc_id asc
2.之后根据得到的排序字段custom_manage_status
进行升序排列