[英]How to sort returned sql result by id that appears the most time in that result
I have table offer_cpv
that is connecting two others " offer
" and " cpv
". 我的表
offer_cpv
连接了另外两个“ offer
”和“ cpv
”。 You can see fiddle here: http://sqlfiddle.com/#!9/02020/1 您可以在这里看到小提琴: http ://sqlfiddle.com/#! 9/02020/1
offer_cpv
has two columns that are important for us: offer_id
and cpv_id
. offer_cpv
有两列对我们来说很重要: offer_id
和cpv_id
。
My starting query looks like this: SELECT cpv_id FROM offer_cpv WHERE offer_id IN (1,2,3,4) LIMIT 10
我的起始查询如下所示:
SELECT cpv_id FROM offer_cpv WHERE offer_id IN (1,2,3,4) LIMIT 10
As you can see I need to return all cpv_id
based on the array of offer_id
( I pass that to WHERE IN (offer_id)
. 如您所见,我需要根据
cpv_id
数组返回所有offer_id
(我将其传递给WHERE IN (offer_id)
。
I will get this result: 我会得到以下结果:
cpv_id
1010
1020
1030
2010
4030
4060
1010
2010
1010
1020
As you can see some cpv_id are repeating because several offers may have same cpv_id linked to them. 如您所见,有些重复的cpv_id重复出现,因为几个商品可能链接了相同的cpv_id。 I need to get list of "most popular" cpv_id, I mean if some id is repeating the most time I need it to be on top of list.
我需要获取“最受欢迎” cpv_id的列表,这意味着如果某些ID重复最多的时间,则我需要它位于列表顶部。 For example, this would be desired output:
例如,这将是期望的输出:
cpv_id
1010
1020
2010
1030
4030
4060
As you can see 1010 is repeating 3 times so I want it on top of returned result. 如您所见1010重复3次,因此我希望它位于返回结果的顶部。 Then comes 1020 and 2010 since they are repeating 2 times, an then come others until limit of 10 is reached.
然后是1020和2010,因为它们重复了2次,然后又出现了,直到达到10个极限。
Is this possible to do somehow with MYSQL and PHP ? 这可能以某种方式使用MYSQL和PHP吗?
Thanks 谢谢
You need count(*)
and group by
您需要
count(*)
并group by
SELECT cpv_id,count(*) as tot FROM offer_cpv
WHERE offer_id IN (1,2,3,4)
group by cpv_id
order by tot desc
LIMIT 10
http://sqlfiddle.com/#!9/02020/3 http://sqlfiddle.com/#!9/02020/3
You can use distinct to get only unique values. 您可以使用distinct仅获取唯一值。 Here is your query:
这是您的查询:
SELECT
distinct cpv_id
FROM
offer_cpv
WHERE
offer_id IN (1,2,3,4)
LIMIT 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.