在条件中按顺序选择查询

时间:2013-02-26 22:05:47

标签: java hibernate criteria

我想从这个SQL查询创建一个条件查询:

SELECT * FROM `Product` p
ORDER BY (SELECT COUNT(*) FROM `Sale` WHERE `product_id` = p.id) DESC

我无法通过子查询找到方法...

2 个答案:

答案 0 :(得分:1)

尝试隐式联接:

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

答案 1 :(得分:1)

Order By仅适用于select部分中的列。

所以基本上这样的事情会起作用:

SELECT Group, COUNT(*) as total
FROM table
GROUP BY Group
ORDER BY total DESC

因此,对于您的情况,您可以执行以下操作:

SELECT *, (SELECT COUNT(*) FROM `Sale` WHERE `product_id` = p.id) as total FROM `Product` p
ORDER BY total DESC

注意:这是完全未经测试的。