php查询从数据库中排序结果

时间:2014-06-22 21:50:31

标签: php mysql sql

是否有可能通过时间戳进行查询以获得前3个评论ORDER BY评级和其余评论?

我使用简单的查询来获取我的脚本的评论,我按时间戳排序,这是示例

mysql_query("SELECT * FROM comments WHERE content = '$id' AND approved='1' AND parent_id ='0' ORDER BY timestamp DESC"); 

默认情况下,所有评论在数据库中都有0评级

1 个答案:

答案 0 :(得分:3)

下面的查询将前3个评论评论作为前3行返回,最新评论不包括前3个评论。

SELECT t1.* 
FROM 
(
    SELECT t2.* FROM (
      SELECT c.* , my_order 1 FROM comments c
      WHERE content = '$id'
          AND approved = '1' 
          AND parent_id = '0'
      ORDER BY rating DESC LIMIT 3
    ) t2
    UNION
    SELECT c.* , my_order 2 FROM comments c
    WHERE content = '$id' 
        AND approved = '1' 
        AND parent_id = '0' 
        AND id NOT IN (
            SELECT id FROM comments
            WHERE content = '$id'
              AND approved = '1' 
              AND parent_id = '0'
            ORDER BY rating DESC LIMIT 3
        )
) t1
ORDER BY 
    my_order, 
    (CASE WHEN my_order = 1 THEN rating ELSE timestamp END)