关于数据库: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

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

结果显示,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去重。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理