我想从这个SQL查询创建一个条件查询:
SELECT * FROM `Product` p
ORDER BY (SELECT COUNT(*) FROM `Sale` WHERE `product_id` = p.id) DESC
我无法通过子查询找到方法...
答案 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
注意:这是完全未经测试的。