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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With