加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用复杂的ORDER BY进行MySQL查询

发布时间:2020-12-13 22:45:29 所属栏目:PHP教程 来源:网络整理
导读:我有以下查询: SELECT id,title,adcontent,adtargetURL,locationpage,locationarg,locationid,displayorder,visible,schedstart,schedstop,created,modified,createdby,modifiedbyFROM ads ORDER BY locationpage,title 我需要按以下方式订购字段: 按位置
我有以下查询:

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

我需要按以下方式订购字段:

>按位置排序,首先选择值为’all’的任何字段,然后按升序排序
>然后通过locationarg首先使用任何NULL或空字符串值,然后在asc中使用其余值
>然后通过locationid首先使用任何NULL或0值,其余部分在asc中
>并在其中,首先按’1’的显示顺序排序,然后按NULL,然后按’2’排序
>最后,如果其中任何一个都设置为相同,则通过ASC中的标题

我的ORDER BY应该如何实现这一目标?

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

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

……但这不起作用!

解决方法

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

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

FROM ads            

ORDER BY OrderID DSEC

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读