按时间戳排序记录,但首先列出指定的ID

时间:2011-06-01 16:33:33

标签: php mysql sql-order-by

的MySQL

+----+------------+
| id | timestamp  |
+----+------------+
| 1  | 1306922400 |
+----+------------+
| 2  | 1306926000 |
+----+------------+
| 3  | 1306929600 |
+----+------------+

PHP

$a = mysql_query("SELECT * FROM `table` ORDER BY ?? DESC, `timestamp` DESC");

按顺序排序:

  1. id等于2

  2. 开始
  3. 然后按timestamp

  4. 排序

    订单应该是:2,3,1

4 个答案:

答案 0 :(得分:1)

你可以使用UNION ......但我会避免它。

$a = mysql_query("
                  (SELECT * FROM `table` WHERE id = 2 ) UNION 
                  (SELECT * FROM table ORDER BY timestamp DESC)
                ");

考虑到我在第二个查询中没有UNION ALL,id = 2的记录将不会重复。

答案 1 :(得分:1)

SELECT * FROM `table` where id = 2
union 
SELECT * FROM `table` where id != 2 order by id, timestamp desc

答案 2 :(得分:0)

SELECT * FROM `table` ORDER BY `id`!=2 ASC,  `timestamp` DESC
// or
SELECT * FROM `table` ORDER BY `id`=2 DESC,  `timestamp` DESC

答案 3 :(得分:-1)

$a = mysql_query("SELECT * FROM `table` WHERE id = 2 ORDER BY `timestamp` DESC UNION SELECT * FROM `table` WHERE id != 2 ORDER BY `timestamp DESC");