Reputation: 691
I'd like to create a criteria query from this SQL query :
SELECT * FROM `Product` p
ORDER BY (SELECT COUNT(*) FROM `Sale` WHERE `product_id` = p.id) DESC
I cannot find a way to do it with the sub query...
Upvotes: 0
Views: 199
Reputation: 12010
Order By
is only applicable for a column which is present in the select
part.
So basically something like this will work:
SELECT Group, COUNT(*) as total
FROM table
GROUP BY Group
ORDER BY total DESC
So for your case, you can do something like following:
SELECT *, (SELECT COUNT(*) FROM `Sale` WHERE `product_id` = p.id) as total FROM `Product` p
ORDER BY total DESC
Note: This is completely untested.
Upvotes: 1
Reputation: 1367
Try an implicit join:
select *
from (
select
p.*,
(select count(*) from sale s where s.product_id = p.id) as cnt
from product p
)a
order by cnt desc
Upvotes: 1