douye9822 2013-11-18 09:21
浏览 31
已采纳

将排序算法应用于数据库查询[关闭]

I want to make another list with "What's Hot" like reddit.

I found this topic where it explains how their sorting algorithm works

First I want to ask, if it is legal to use their algorithm?

And if yes, how would I apply it to PHP database query. Do I need to SELECT all posts first and then sort it?

function hot($ups, $downs, $date) {
    $s = $ups - $downs;
    $order = log(max(abs(s), 1), 10);
    if(s > 0) {
        $sign = 1;
    } elseif(s < 0) {
        $sign = -1;
    } else {
        $sign = 0;
    }
    $date = new DateTime($date);
    $seconds = $date->format('U');
    return round($order + $sign * $seconds / 45000, 7);
}

this is what I get when I convert it to PHP.

  • 写回答

1条回答 默认 最新

  • duan6301 2013-11-18 20:40
    关注

    Assuming your ups and downs columns are called ups and downs, then something like:

    ORDER BY ROUND(
        ( LOG10(
              GREATEST(
                  ABS(`ups` - `downs`), 
                  1
              )
          ) + 
          SIGN(`ups` - `downs`) *
          UNIX_TIMESTAMP(`date_posted`)  / 45000
        ),
        7
    )
    

    It might be a better idea to use this formula to create a calculated column in your select list, and then order by that column

    EDIT

    Example of a calculated column:

    SELECT `ups`,
           `downs`,
           `posted_date`,
           ROUND(
               ( LOG10(
                   GREATEST(
                       ABS(`ups` - `downs`), 
                       1
                   )
                 ) + 
                 SIGN(`ups` - `downs`) *
                 UNIX_TIMESTAMP(`date_posted`)  / 45000
               ),
               7
           ) AS hotness
      FROM `posts`
    

    So hotness is your calculated column

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么