我在我的数据库中有一个已售出的表,我的表看起来像这样:
+-----------+---------------------+---------+---------+
| id | product_id | user_id | date |
+-----------+---------------------+---------+---------+
| 1 | 20 | 2 |392185767|
+-----------+---------------------+---------+---------+
| 2 | 28 | 3 |392333337|
+-----------+---------------------+---------+---------+
我想要按大多数购买的产品对表输出进行排序 类似的东西:
$sql = "select * from sold order by most_repeated(product_id)";
我不想按产品ID对输出进行分组,我只是想对它们进行排序,以便最重复的产品显示在结果的顶部
答案 0 :(得分:2)
由于您不想分组,您可以使用相关查询:
select * from sold s
order by (select COUNT(1) from sold ss where ss.product_id=s.product_id)
我没有在MySQL中尝试这个,但它应该可以工作。
答案 1 :(得分:0)
你根本找不到重复的产品而不计算它。
SELECT product_id, COUNT(product_id) AS product_count
FROM sold
GROUP BY product_id
ORDER BY product_count DESC;
答案 2 :(得分:0)
此查询应该可以为您提供所需的内容,而无需多次计算同一产品。
select s.*
from sold s join
(select count(product_id) as times_purchased, product_id
from sold
group by product_id) most_repeated on s.product_id = most_repeated.product_id
order by most_repeated.times_purchased
祝你好运!