语句/多个时的ORDER BY case

时间:2018-04-04 18:22:27

标签: php mysql sql mysqli

我想在我的请求中添加一个条款:

SELECT * FROM MV_immo 
WHERE bien != 'Autre' AND bien != 'Indifférent' 
ORDER BY case
    when vendue = 'AV' then 1
    when vendue = 'VPNA' then 2
    when vendue = 'EC' then 3
else 6 end, Id DESC LIMIT 0,6

现在,我有一个列“position”(int),我想保留第一个订单并添加ORDER“position”子句(类似这样......):

SELECT * FROM MV_immo 
WHERE bien != 'Autre' AND bien != 'Indifférent' 
ORDER BY case
    when vendue = 'AV' AND position ASC then 1
    when vendue = 'VPNA' AND position ASC then 2
    when vendue = 'EC' AND position ASC then 3
else 6 end, Id DESC LIMIT 0,6

或者......或者......

SELECT * FROM MV_immo 
WHERE bien != 'Autre' AND bien != 'Indifférent' 
ORDER BY case
when vendue = 'AV', position ASC then 1
when vendue = 'VPNA', position ASC then 2
when vendue = 'EC', position ASC then 3
else 6 end, Id DESC LIMIT 0,6

我的目标是保留第一个订单(ORDER BY vendue)并添加第二个ORDER子句:position。
我需要你的帮助才能解决这个问题我正在启动php而且这对我来说并不简单。
我该怎么做? 感谢。

1 个答案:

答案 0 :(得分:4)

如果我理解正确,你想:

ORDER BY (case when vendue = 'AV' then 1
               when vendue = 'VPNA' then 2
               when vendue = 'EC' then 3
               else 6
          end),
         position,
         Id DESC

如果您愿意,可以缩短:

order by field(vendue, 'EC', 'VPNA', 'AV') desc, position, id

请注意,field()来电中的值为反向顺序。