ORDER BY子句中的SQL条件

时间:2018-04-03 01:08:55

标签: mysql sql

我在这里有这个问题:

SELECT posts.id, username, cover, audio, title, postDate, commentsDisabled,
       MAX(postClicks.clickDate) as clickDate,
       COUNT(*) as ClickCount
FROM postClicks INNER JOIN
     posts
     ON posts.id = postClicks.postid INNER JOIN
     users
     ON users.id = posts.user
WHERE posts.private = 0
GROUP BY postClicks.postid
ORDER BY ClickCount
LIMIT 5

此查询获取前5个结果ORDER BY Count,即ClickCount。我的数据库中的每个postClicks都有一个clickDate我现在要做的就是我得到的5个结果,在过去24小时内按ClickCount排序,我仍需要5个结果,但它们需要按顺序排列ClickCount,24小时。

我在where子句中使用它:

postClicks.clickDate > DATE_SUB(CURDATE(), INTERVAL 1 DAY)

但是在24小时后我不会得到5个结果,我需要得到5个结果。

我的问题是,我可以在条款或案件中加入条款吗?

1 个答案:

答案 0 :(得分:1)

您无法在此查询的ORDER BY中添加条件,因为这会影响LIMIT。相反,您可以使用子查询:

SELECT pc5.*
FROM (SELECT posts.id, username, cover, audio, title, postDate, commentsDisabled,
             MAX(postClicks.clickDate) as clickDate,
             COUNT(*) as ClickCount,
             SUM(postClicks.clickDate > DATE_SUB(CURDATE(), INTERVAL 1 DAY)) as clicks24hours
      FROM postClicks INNER JOIN
           posts
           ON posts.id = postClicks.postid INNER JOIN
           users
           ON users.id = posts.user
      WHERE posts.private = 0
      GROUP BY postClicks.postid
      ORDER BY ClickCount
      LIMIT 5
     ) pc5
ORDER BY clicks24hours DESC;