mysql基于条件的多订单

ckx4rj1h  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(338)

我有一个如下的查询,当我只按 end_time :
作品

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;

它给了我:
错误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实现与上面相同的查询

nbysray5

nbysray51#

如果你只是想点菜的话 table1.start_time 以及什么时候 table1.status = 'f1' ,您只需添加另一个,如果:

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;
70gysomp

70gysomp2#

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

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;

相关问题