C/C++教程

order by和distinct导致结果显示顺序有问题

本文主要是介绍order by和distinct导致结果显示顺序有问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SQL如下

SELECT DISTINCT
	a.id,
	a.num
FROM
	 a
LEFT JOIN   d ON a.id = d.stockId
WHERE
	a.cid = 156662
AND a.status = 3
AND d.wid IN (
	123,
)
ORDER BY
	a.num DESC
LIMIT 0,10

file

分析

去掉limit,查看num大于0的值很多,怎么会取不到?
file

结果显示,distinct对id进行了重新排序导致,最后limit取了重新排序后的前10条数据。
解决方案修改sql:

  1. distinct换成group by
  2. order by a.num desc 换成order by a.num desc,a.id

总结

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

这篇关于order by和distinct导致结果显示顺序有问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!