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