Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply ORDER BY after query and LIMIT

Have found similar posts but still stuck - I am trying to apply a sort AFTER I have processed a query and limited the results. My code is

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

I have tried doing a sub select and applying the ORDER BY afterwards but get an error saying Unknown column 't.id' in 'field list'.

The above code (ie without the sub select) works fine but the ORDER BY slows it down so much as the table is huge... Any suggestions?

like image 554
southafricanrob Avatar asked Oct 03 '22 16:10

southafricanrob


1 Answers

Since you're aliasing t.id to t_id, you need to use the alias in the outer query.

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

BTW, the way you wrote DISTINCT(t.id) suggests that you think the distinct operation is only being applied to that one column. DISTINCT applies to the entire SELECT list; if you only want to make certain columns distinct, you must use GROUP BY to specify those columns.

Here's a possible way to rewrite the query that may make it faster:

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

By filtering down to just the top 500 IDs, the size of the joins and sorting are reduced.

like image 181
Barmar Avatar answered Oct 07 '22 20:10

Barmar