【问题标题】:Apply ORDER BY after query and LIMIT在查询和限制后应用 ORDER BY
【发布时间】:2023-03-14 19:48:01
【问题描述】:

找到了类似的帖子,但仍然卡住 - 我在处理查询并限制结果后尝试应用排序。我的代码是

select DISTINCT(t.id) t_id, t.cart_id ,tS.id tS_id, tS.created tS_created, t.value, t.transactionType_id tT_id, tS.member_name, outIn, tT.type type

                            from(transaction t)
                            join transactionSummary tS ON tS.id = t.transactionSummary_id
                            left join transactionType tT ON tT.id = t.transactionType_id
                            order by t.id DESC
                            limit 50

我曾尝试进行子选择并在之后应用 ORDER BY,但收到错误提示“字段列表”中的未知列“t.id”。

上面的代码(即没有子选择)工作正常,但 ORDER BY 减慢了它的速度,因为表很大...... 有什么建议吗?

【问题讨论】:

    标签: mysql sql-order-by limit


    【解决方案1】:

    由于您将 t.id 别名为 t_id,因此您需要在外部查询中使用别名。

    SELECT *
    FROM (select DISTINCT t.id t_id, t.cart_id ,tS.id tS_id, tS.created tS_created, t.value, t.transactionType_id tT_id, tS.member_name, outIn, tT.type type
    
        from transaction t
        join transactionSummary tS ON tS.id = t.transactionSummary_id
        left join transactionType tT ON tT.id = t.transactionType_id
        limit 50) x
    ORDER BY t_id DESC
    

    顺便说一句,您编写DISTINCT(t.id) 的方式表明您认为 distinct 操作仅应用于那一列。 DISTINCT 适用于整个SELECT 列表;如果您只想区分某些列,则必须使用GROUP BY 指定这些列。

    这是一种可能的方式来重写查询,可能会使其更快:

    select DISTINCT t.id t_id, t.cart_id ,tS.id tS_id, tS.created tS_created, t.value, t.transactionType_id tT_id, tS.member_name, outIn, tT.type type
    from transaction t
    join (select max(id)-500 maxid from transaction) mT on t.id > maxid
    join transactionSummary tS ON tS.id = t.transactionSummary_id
    left join transactionType tT ON tT.id = t.transactionType_id
    order by t_id DESC
    limit 50
    

    通过过滤到仅前 500 个 ID,连接和排序的大小减少了。

    【讨论】:

    • 啊哈 - 有道理 re DISTINCT,感谢您的帮助...我仍然只获得表中的前 50 行与该查询,我正在寻找的是获得最后 50 行(即最近的)
    • @user2894986 在内部查询的 LIMIT 之前添加order by t.id DESC,因为它在您的内部查询中,它将按您的预期工作。
    • @valex 在他的原始查询中就是这样,但这不是他想要的。
    • 我忘了DESC关键字,我修好了。
    • 通过将 LIMIT 移动到子查询中,它会选择 50 个任意行,然后对它们进行排序。您的原始查询找到了最近的 50 个,但您说您不想要那个。
    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 2016-11-13
    • 2012-10-28
    • 2013-10-19
    • 2020-11-19
    • 2021-11-17
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多