SQL - 按 2 列排序 - 排序主题(先固定,然后按创建的时间戳)
SQL - order by 2 columns - order topics ( pinned first, then by created timestamp)
我有 1 table 个主题。
我想用这种方式对行进行排序。
首先获取 pinned = 1
按 id ASC
排序的行
second 将是 pinned = 0
按 created_ts DESC
排序的行
代码:
SELECT topics
WHERE category_id = :i AND deleted = :d
ORDER BY pinned ASC, created_ts DESC
注意:我错误地切换了 table 中的列 ( edited_by <=> edited_ts )
如果另一列满足特定条件,您应该能够使用 CASE
仅按列排序:
SELECT id, title, ...
FROM topics
WHERE category_id = :i AND deleted = :d
ORDER BY pinned DESC, -- first 1 then 0
CASE WHEN pinned = 1 THEN id ELSE 0 END, -- ignore for pinned=0
created_ts DESC
这样的事情怎么样:
SELECT ...
ORDER BY pinned DESC,
CASE WHEN pinned = 1
THEN id
ELSE -created_ts
DESC
我有 1 table 个主题。
我想用这种方式对行进行排序。
首先获取 pinned = 1
按 id ASC
second 将是 pinned = 0
按 created_ts DESC
代码:
SELECT topics
WHERE category_id = :i AND deleted = :d
ORDER BY pinned ASC, created_ts DESC
注意:我错误地切换了 table 中的列 ( edited_by <=> edited_ts )
如果另一列满足特定条件,您应该能够使用 CASE
仅按列排序:
SELECT id, title, ...
FROM topics
WHERE category_id = :i AND deleted = :d
ORDER BY pinned DESC, -- first 1 then 0
CASE WHEN pinned = 1 THEN id ELSE 0 END, -- ignore for pinned=0
created_ts DESC
这样的事情怎么样:
SELECT ...
ORDER BY pinned DESC,
CASE WHEN pinned = 1
THEN id
ELSE -created_ts
DESC