按同一字段排序,left join 之后顺序与原表直接排序不一致,left join与distinct处理数据重复(统计场景) distinct排序时会对id优化,导致顺序不一致

问题由来:一次性插入多条数据,插入时顺序正常,id正常,但id大的更新时间小! 

SELECT
	* 
FROM
	t_product_events 
WHERE
	product_id = 1344663677526016 
ORDER BY
	update_time DESC

SELECT DISTINCT
	pe.id,
	pe.product_id,
	pe.identifier,
	pe.NAME,
	pe.description,
	pe.type,
	pe.original_required,
	pe.update_required,
	pe.custom,
	pe.copyright,
	pe.prerelease,
	pe.method,
	pe.LEVEL,
	pe.create_time,
	pe.update_time,
	( SELECT count( * ) FROM t_product_events_params WHERE ref_id = pe.id ) AS outNum 
FROM
	t_product_events pe
	LEFT JOIN t_product_events_params pep ON pe.id = pep.ref_id 
WHERE
	pe.product_id = 1344663677526016 
ORDER BY
	pe.update_time DESC

批量插入的数据为红色方框中的

 左表数据:

连接表数据:

左连接不带distinct查询语句:

SELECT 
	pe.id,
	pe.product_id,
	pe.identifier,
	pe.NAME,
	pe.description,
	pe.type,
	pe.original_required,
	pe.update_required,
	pe.custom,
	pe.copyright,
	pe.prerelease,
	pe.method,
	pe.LEVEL,
	pe.create_time,
	pe.update_time,
	( SELECT count( * ) FROM t_product_events_params WHERE ref_id = pe.id ) AS outputData 
FROM
	t_product_events pe
	LEFT JOIN t_product_events_params pep ON pe.id = pep.ref_id 
WHERE
	pe.product_id = 1344663677526016 
ORDER BY
	pe.update_time DESC

不带distinct:

 带上distinct:

distinct对id进行了重新排序导致!!!

解决方案修改sql:

  1. distinct换成group by

  2. order by pe.create_time desc 换成order by pe.create_time desc,pe.id

修改方案后的SQL语句:

SELECT
DISTINCT
	pe.id,
	pe.product_id,
	pe.identifier,
	pe.NAME,
	pe.description,
	pe.type,
	pe.original_required,
	pe.update_required,
	pe.custom,
	pe.copyright,
	pe.prerelease,
	pe.method,
	pe.LEVEL,
	pe.create_time,
	pe.update_time,
	( SELECT count( * ) FROM t_product_events_params WHERE ref_id = pe.id ) AS outputData 
FROM
	t_product_events pe
	LEFT JOIN t_product_events_params pep ON pe.id = pep.ref_id 
WHERE
	pe.product_id = 1344663677526016 
ORDER BY
	pe.update_time DESC,pe.id
	

结果

 

 

总结

distinct id,会对id进行重新排序,如果分页结果显示顺序会有问题。 order by避免和distinct一起使用,尽量和group by去重。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值