[英]How to select from a selection?
I'm creating a commenting system, which will have 2 top comments. 我正在创建一个评论系统,其中将有2条顶级评论。
How can I select the latest 20 rows, and then from that selection, select the top 2 rows (likes-dislikes)? 如何选择最近的20行,然后从该选择中选择前2行(“喜欢”-“不喜欢”)? I can do it with a PHP loop, but it would not be as efficient. 我可以使用PHP循环来做到这一点,但是效率不高。 Currently I am just selecting the top 2 from the all the comments, but the two top comments never change, since people just up-vote those ones: 目前,我只是从所有评论中选择前2个,但是前2个评论永远都不会改变,因为人们只是投票赞成那些评论:
SELECT * FROM pagecomments WHERE page_id='$pageid' ORDER BY likes-dislikes DESC LIMIT 2
EDIT: The table is ordered by the the column "id", which is auto_increment. 编辑:该表是由列“ id”,即auto_increment排序的。 page_id is the page on the site. page_id是网站上的页面。 Sorry. 抱歉。
Nest your query: 嵌套查询:
SELECT *
FROM (
SELECT *
FROM pagecomments
WHERE page_id='$pageid'
ORDER BY date DESC
LIMIT 20
) t
ORDER BY likes-dislikes DESC
LIMIT 2
Order not only by LIkes, first order by date entered or timestamp. 不仅可以按订单排序,还可以按输入的日期或时间戳排序。 By ordering by date, you assure that you`ll get the latest 20 posts or comments. 通过按日期排序,您可以确保获得最新的20条帖子或评论。
SELECT * FROM pagecomments WHERE page_id='$pageid' ORDER by date_entered desc ,
likes-dislikes DESC limit 2
Since your id
column is set to auto_increment
, use it in a subquery: 由于您的id
列设置为auto_increment
,因此可以在子查询中使用它:
select *, likes-dislikes
from (
select *
from pagecomments
where page_id='$pageid'
order by id desc
limit 20
) t
order by likes-dislikes desc
limit 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.