2012-10-05 70 views
4

我有以下查询:MySQL查询复杂ORDER BY

SELECT id, title, adcontent, adtargetURL, locationpage, 
locationarg, locationid, displayorder, visible, schedstart, 
schedstop, created, modified, createdby, modifiedby 
FROM ads    
ORDER BY locationpage, locationarg, locationid, title 

我需要订购的字段方式如下:

  • 排序与“所有的价值的任何领域locationpage '第一,那么剩下的以升序
  • 然后通过在与任何NULL或空字符串值locationarg第一,然后在递增
  • 其余然后通过locationid与任何NULL第一或0的值,其余的SC
  • 和内的那些,排序由displayorder的“1”,然后再NULL,则“2”
  • 以及最后,通过在ASC标题如果任何这些管理对全部相同

我的ORDER BY应该怎样实现这个目标?

这是我到目前为止有:(从下面更新)

ORDER BY locationpage='all', 
     locationpage ASC, 
     locationarg ASC, 
     locationid ASC, 
     displayorder='1', 
     ISNULL(displayorder), 
     displayorder='2', 
     title ASC 

...但是这是行不通的!

+0

除了'locationpage'之外,其他排序顺序只是' ASC' afaik,或者只是''。 –

+0

真的!我不知何故按字母顺序忘记了null/empty值。现在我有这样的: 'ORDER BY locationpage = '全部', \t \t \t locationpage ASC, \t \t \t locationarg ASC, \t \t \t locationid ASC, \t \t \t displayorder = '1', \t \t \t ISNULL(displayorder), \t \t \t displayorder ='2', \t \t \t title ASC' – Michelle

+0

我认为需要'UNION'的组合。 – hjpotter92

回答

1

你最好的选择是使用一个计算的字段会根据您的规则生成订单ID。我将在稍后添加一个例子..

select 
case 
    when locationpage = "all" then 10 
    when ISNULL(locationarg) then 20 
    .... 
    else 50 
end as OrderID, 
id, 
title, 
.... 

FROM ads    

ORDER BY OrderID DSEC 
+0

在您的订单标识符10用乘法来算,如果你愿意,这将在未来帮助需要对两个值之间的东西进行sqeeze ... – Mortalus

0

给这一个bash:

select id, title, adcontent, adtargetURL, locationpage, locationarg, locationid, displayorder, visible, schedstart, schedstop, created, modified, createdby, modifiedby 
from ads 
order by case when locationpage='all' then 0 else 1 end, 
     locationpage, 
     case when locationarg is null or locationarg='' then 0 else 1 end, 
     locationarg ASC, 
     case when locationid is null OR locationid='0' then 0 else 1 end, 
     locationid, 
     case when displayorder =1 then 0 when displayorder is null then 1 when displayorder = 2 then 2 else 3 end, 
     title;