一个示例表:
NAME, PRIORITY, SORT
TEST1, 0, 11:10
TEST2, 1, 11:15
TEST3, 0, 11:20
TEST4, 1, 11:30
我想通过订购来列出以下优先级列表priority
:
TEST2 (first submitted with priority)
TEST1
TEST3
TEST4
怎么做?我已经尝试过使用 GROUP BY 等,但没有成功!
请试试这个。
SELECT NAME
FROM table
WHERE PRIORITY = 1
ORDER BY TIME ASC
LIMIT 1
UNION
SELECT NAME
FROM table
ORDER BY TIME ASC
那应该给
TEST2 (first submitted with priority) TEST1 TEST3 TEST4
编辑忘记优先级
根据http://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/您不能在工会的相对两侧有两个单独的订单。但是您可以做的是添加一个新列并按该列排序。
该网站建议类似(虽然这是用于 sql server,但我不知道 mysql 是否使用相同的语法)
Select name, priority, sort, '1' OrderKey from table where priority = 1 and sort <= (select min(t3.sort) from table t3 where t3.priority = 1)
union
select name, priority, sort, '2' OrderKey from table
order by OrderKey, time asc
同样,这适用于 sql server,但不确定它是否适用于 mysql。
编辑:固定查询(希望...)
CREATE TABLE `name_priority_sort` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(31) DEFAULT NULL,
`priority` int(11) DEFAULT NULL,
`sort` time DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `name_priority_sort` (`id`, `name`, `priority`, `sort`)
VALUES
(1,'Test1',0,'11:10:00'),
(2,'Test2',1,'11:15:00'),
(3,'Test3',0,'11:20:00'),
(4,'Test4',1,'11:30:00');
select `name`, priority, sort from (
select 1 `set`, `name`, priority, min(sort) sort from `name_priority_sort` where priority = 1
union all
select 2 `set`, `name`, priority, sort from `name_priority_sort` where `name` not in (
select `name` from (
select `name`, priority, min(sort) sort from `name_priority_sort` where priority = 1
) first_set
)
) sets
order by `set`, sort
-- results
name priority sort
Test2 1 11:15:00
Test1 0 11:10:00
Test3 0 11:20:00
Test4 1 11:30:00