sql获取最常用的记录

时间:2015-02-25 20:56:40

标签: mysql

在我的应用程序中,每个用户都可以拥有自己的产品愿望清单。 我想获得5个最常用的记录,但...... 愿望清单表获取列:

  1. ID
  2. USER_ID
  3. PRODUCT_ID
  4. 位置!!
  5. 排名是产品在愿望清单中显示的顺序。 每个位置都获得积分,例如产品在第一个位置得到9分,第二个8分(...)第十个位置,每隔一个结束,得到0分。

    所以换句话说,我想获得5条具有最高值sum(count()* position_point)的记录,产品由product_id

    组成

    这只能在sql中使用吗?或者我应该使用php来获取正确的记录?

    类似的东西:

        select product_id, CASE position WHEN 1 THEN 9 * (select count(id) as countie from product_wishlist b where position <10 and a.product_id = b.product_id and  a.position = b.position  group by product_id) end as summary
    from product_wishlist a
    

    能正常工作并且相当优化吗?只是添加其余的案例条件?

    编辑:和product_id上的不同

1 个答案:

答案 0 :(得分:0)

你可以更简单地写这个:

select product_id,
       sum(greatest(10 - position, 0)) as summary
from product_wishlist pw
group by product_id
order by summary desc
limit 5;
相关问题