MySQL基于条件的多个ORDER BY

时间:2018-04-30 08:21:57

标签: mysql

我有一个如下查询,当我仅按end_time订购该表时,该查询有效:

WORKS

SELECT * FROM table1 WHERE ... ORDER BY field(table1.status, 'c1','a1', 'b1', 'e1',
'd1') asc, IF(table1.status = 'f1', table1.end_time, '') asc LIMIT 20 OFFSET 0;

但是,如果我想在条件排序中添加一个列,例如:

SELECT * FROM table1 WHERE ... ORDER BY field(table1.status, 'c1', 'a1', 'b1', 'e1',
'd1') asc, IF(table1.status = 'f1', (table1.end_time, table1.start_time), '') asc
LIMIT 20 OFFSET 0;

它给了我:

  

ERROR 1241(21000):操作数应包含1列

但是,以下没有 IF 的查询有效:

SELECT * FROM table1 WHERE ... ORDER BY field(table1.status, 'c1', 'a1', 'b1', 'e1',
'd1') asc, table1.end_time, table1.start_time asc LIMIT 20 OFFSET 0;

如何使用 IF

实现与上述相同的查询

2 个答案:

答案 0 :(得分:2)

如果您只想在table1.start_time时按table1.status = 'f1'订购,则只需添加其他IF:

SELECT * 
FROM table1 
WHERE ... 
ORDER BY field(table1.status, 'c1','a1', 'b1', 'e1','d1') asc,
    IF(table1.status = 'f1', table1.end_time, '') asc,
    IF(table1.status = 'f1', table1.start_time, '') asc
LIMIT 20 OFFSET 0;

答案 1 :(得分:0)

我认为我找到了一个解决方案,它在重复代码时很难看,但是,我仍然期待更好的答案:

现在,我解决了我的问题:

SELECT * FROM table1 WHERE ... ORDER BY field(table1.status, 'c1', 'a1', 'b1', 'e1', 'd1') asc,
IF(table1.status = 'f1', table1.end_time, '') asc,
IF(table1.status = 'f1', table1.start_time, '') asc
LIMIT 20 OFFSET 0;