mysql按字段值优先排序

时间:2015-07-15 07:05:32

标签: mysql sql

好的,我有一个带字段的表

Table: comments
    id (primary key, increment, int)
    post_id(foreign key, int)
    user_id (foreign key, int)
    content (text)
    timestamp

Data
1, 1, 1, hello, timestamp
2, 3, 4, 123, timestamp
3, 1, 5, 1245, timestamp
4, 1, 8, test, timestamp
5, 1, 10, hi, timestamp
6, 3, 1, this is 3, timestamp

即使按时间戳排序,如何在结果中包含user_id 1的情况下选择5个结果?

让我们想一想数据集,最低行(5)有最新的时间戳,而1有最老的时间戳。

我需要id 1(用户ID为1)才能包含在限制5中,即使它的时间戳是最旧的。

预期返回的行ID:

1, 5, 4

5, 4, 3

SQL我没有工作:

SELECT id FROM comments WHERE post_id = 1 ORDER BY user_id = 1, timestamp DESC DESC LIMIT 3

我该怎么做

1 个答案:

答案 0 :(得分:1)

您可以按user_id = 1订购:

SELECT stuff
FROM comments
ORDER BY user_id = 1 DESC, timestamp DESC
LIMIT 3

这可以通过以下方式工作: order by子句:user_id = 1将评估为true(或1更明显的)第一个ID和false(或0)其他行,因为他们有其他user_ids。因此,您有01的imanginary字段,这些字段的排序为DESC,返回

+----+------+-------------+------------------------+
| id | user | user_id = 1 |       timestamp        |
+----+------+-------------+------------------------+
|  1 |    1 |           1 | oldest timestamp       |
|  5 |   10 |           0 | newest timestamp       |
|  4 |    8 |           0 | some timestamp between |
+----+------+-------------+------------------------+