0

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

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

我找不到使用子查询的方法...

4

2 回答 2

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
于 2013-02-26T22:13:15.640 回答
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

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

于 2013-02-26T22:13:26.510 回答