1

I'm having problems with my query, basically what I'm trying to do here is to order first by

item_info.content_time desc

and then by

item_views.views desc

My intention is to get the most recent items (order by item_info.content_time desc), with the most views (item_views.views desc). In essence something like the stackoverflow main page, where you have the most recent with the most views (I really don't know if that's how they are doing it). The following query either orders the items by one criteria or the other (if I reverse the order by criteria). Here's my code:

SELECT item_info.item_id, item_info.profile_id, item_info.tittle, item_covers.reference, usuarios.username, item_views.views
FROM item_info
LEFT JOIN item_covers ON item_covers.cover_id = item_info.book_id
LEFT JOIN usuarios ON item_info.profile_id = usuarios.id
LEFT JOIN item_views ON item_views.id = item_info.book_id
WHERE item_info.content_time
BETWEEN UNIX_TIMESTAMP( CURDATE( ) + INTERVAL -1
DAY )
AND UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1
DAY ) 
order by item_info.content_time desc, item_views.views desc

Roughly something like...

Expected output:

content_time    |      views

17:00                      500
13:00                      300
11:00                      100
10:00                      50

Actual output:

content_time    |      views

17:00                      500
16:00                      10
15:00                      30
14:00                      50

4

2 回答 2

1

如果您想要两者的组合,您应该创建一个由两者的组合(可能由额外因素加权)和组成的列 like DATEDIFF(content_time,NOW())+views。通过使用 DATEDIFF,您将确保它content_time是数字类型并且可以添加到views. 通过DATEDIFF()以显示的顺序使用参数,您将获得过去任何 s 的负数,content_time这将views相应地减少组合值。

所以你的查询应该以这样的结尾

..
...
ORDER BY DATEDIFF(viewsitem_info.content_time,NOW())+viewsitem_info.views desc

DATEDIFF()给出天数的差异。也许你想更精确一点。在这种情况下,您可能想TIMESTAMPDIFF(MINUTE,viewsitem_info.content_time,NOW())改用。

@Aaron:您根本不必更改数据结构。如有必要,您应该引入某种称重因子,例如

ORDER BY 
(0.123* TIMESTAMPDIFF(MINUTE,viewsitem_info.content_time,NOW()) 
      + viewsitem_info.view) DESC
于 2013-08-07T05:32:36.440 回答
0

像下面这样写你的查询

SELECT item_info.item_id, item_info.profile_id, item_info.tittle, item_covers.reference,
usuarios.username, item_views.views FROM item_info
LEFT JOIN item_covers ON item_covers.cover_id = item_info.book_id
LEFT JOIN usuarios ON item_info.profile_id = usuarios.id
LEFT JOIN item_views ON item_views.id = item_info.book_id
WHERE item_info.content_time
BETWEEN UNIX_TIMESTAMP( CURDATE( ) + INTERVAL -1DAY )
    AND UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1
 DAY ) 
order by item_info.content_time,item_views.views desc

我认为它会工作。

于 2013-08-07T05:54:59.163 回答