如何在mysql中对两列进行排序

时间:2016-05-23 02:40:37

标签: mysql

我有这个项目表。

SELECT * FROM项目按order排序;

返回数据:

| itemID  |   order  | description |    date_ordered       |
|   1     |    1     |   Apple     |  2016-05-26 08:00:00  |
|   2     |    1     |   Banana    |  2016-05-22 10:00:00  |
|   3     |    2     |   Cocoa     |  2016-05-29 08:00:00  |
|   4     |    3     |   Lychee    |  2016-05-30 12:00:00  |

预期输出:

| itemID  |   order  | description |    date_ordered       |
|   1     |    1     |   Apple     |  2016-05-26 08:00:00  |
|   3     |    2     |   Cocoa     |  2016-05-29 08:00:00  |
|   4     |    3     |   Lychee    |  2016-05-30 12:00:00  |
|   2     |    1     |   Banana    |  2016-05-22 10:00:00  | <-- This is expired

我被订单困住了。也许有人可以帮助我。我不知道mysql中的一些过滤器只是基础知识。

新添加的项目应该位于查询的顶部,如果旧的,它必须位于底部。

2 个答案:

答案 0 :(得分:2)

如果我理解你想要什么,你可以试试这个:

SELECT * FROM items ORDER BY (date_ordered < now()), `order`;

当“通过比较排序”时,结果为“ split ”。然后您可以根据您选择的标准订购。但是,比较必须是第一个标准。

答案 1 :(得分:1)

@Arcesilas的答案绝对正确,但如果新订单在now()之前,以防万一。

SQL Fiddle

MySQL 5.6架构

CREATE TABLE items
    (`itemID` int, `order` int, `description` varchar(6), `date_ordered` datetime)
;

INSERT INTO items
    (`itemID`, `order`, `description`, `date_ordered`)
VALUES
    (1, 1, 'Apple', '2016-05-26 08:00:00'),
    (2, 1, 'Banana', '2016-05-22 10:00:00'),
    (3, 2, 'Cocoa', '2016-05-29 08:00:00'),
    (4, 3, 'Lychee', '2016-05-30 12:00:00')
;

查询1

SELECT items.*
FROM (SELECT * FROM items ORDER BY items.`order`) items
JOIN (
  SELECT `order`, max(date_ordered) AS date_ordered FROM items GROUP BY `order`
) a ON a.`order` = items.`order` AND  a.date_ordered = items.date_ordered
UNION
SELECT items.*
FROM (SELECT * FROM items ORDER BY items.`order`) items
JOIN (
  SELECT `order`, max(date_ordered) AS date_ordered FROM items GROUP BY `order`
) a ON a.`order` = items.`order` AND  a.date_ordered <> items.date_ordered

<强> Results

| itemID | order | description |          date_ordered |
|--------|-------|-------------|-----------------------|
|      1 |     1 |       Apple | May, 26 2016 08:00:00 |
|      3 |     2 |       Cocoa | May, 29 2016 08:00:00 |
|      4 |     3 |      Lychee | May, 30 2016 12:00:00 |
|      2 |     1 |      Banana | May, 22 2016 10:00:00 |