如何通过划分两行来排序sql输出?

时间:2015-07-27 14:57:31

标签: php sql database

我想根据喜欢(投票)除以观点(发布时间)的结果对我网站的帖子进行排序。

这样的事情可能吗?

$sql = "SELECT * 
        from posts 
        WHERE id NOT IN(SELECT postid FROM postfeed)
        ORDER BY vote/postviews 
        DESC LIMIT 1";

这是一个将id添加到另一个Feed表的cron作业,这就是为什么我有一个限制为1的原因。

2 个答案:

答案 0 :(得分:2)

我明白你要做什么。如果你想通过计算订购那么就做这个技巧

$sql = "SELECT p.*, p.vote/p.postviews as average 
       FROM posts p
       WHERE id NOT IN(SELECT postid FROM postfeed)
       ORDER BY average DESC 
       LIMIT 1";

您为每行计算值,然后您应为其创建别名并按此别名排序。

答案 1 :(得分:0)

$sql = "SELECT * 
        from posts 
        WHERE id NOT IN(SELECT postid FROM postfeed)
        ORDER BY vote, postviews 
        LIMIT 1";

您还可以添加一个参数来进行Ascending或Descending排序,如下所示: -

$sql = "SELECT * 
        from posts 
        WHERE id NOT IN(SELECT postid FROM postfeed)
        ORDER BY vote DESC, postviews DESC
        LIMIT 1";

$sql = "SELECT * 
        from posts 
        WHERE id NOT IN(SELECT postid FROM postfeed)
        ORDER BY vote DESC, postviews ASC
        LIMIT 1";

啊虽然@Robert可能会更好地理解这个问题。