php - 如何进行复杂的 SQL 查询

标签 php mysql sql sorting

<分区>

我正在尝试制作一个与 Hacker News 类似的网站我发现这个算法需要帮助我对我网站上的链接进行排序,这里是:

Score = (P-1) / (T+2)^G

where,
P = points of an item (and -1 is to negate submitters vote)
T = time since submission (in hours)
G = Gravity, defaults to 1.8 in news.arc

所以我需要创建一个 SQL 查询,该查询将使用上述等式对数据进行排序,但我不知道该怎么做。这是我的表结构:

Table 1 name: links
Table 1 fields: id, title, url, user_id, created_at

Table 2 name: votes
Table 2 fields: id, user_id, link_id, vote, created_at

在表 2 中,投票可以是三个值之一:1、0、-1

那么这甚至可以用 SQL 来做,还是我必须以其他方式来做?

最佳答案

如果您只想使用 SQL 方法。

首先让每个参数与其表中的候选参数映射:

P votes 表中vote 列的总和。

T 当前日期 - now() 函数 - 减去 links 表中的 created_at 列。

G 常数。

考虑到这一点,下面的 SQL 选择语句应该返回每个链接的分数。

select links.id, (sum(vote) - 1) / POWER(DATEDIFF(now(),links.created_at)*24 + 2, 1.8)
from links, votes
where links.id = votes.link_id
group by links.id

sum(投票) ==> P

DATEDIFF(now(),links.created_at)*24 ==> T

1.8 ==> G

关于php - 如何进行复杂的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686709/

相关文章:

php - 表名的 laravel mysql 列

PHP OOP 设计模式 : Should I Create two separate classes for registration and form validation?

php - SQLSTATE[42000] SELECT 中的违规 1064

mysql - 下上功能在字符串搜索中不起作用

php - Yii模型()方法findBySQL( 'SELECT MAX(id) FROM ee_car_types;');

PHP 或 Javascript 将数据格式化为可显示的输出?

php - 从 Excel 导入数据有困难

mysql - 如何更改MySQL Server 8.0的root密码

sql - 如何有效地将我的数据与远程数据库进行比较?

c# - 不能使用空对象或列名称。如有必要,请使用单个空格