mysql order field_MySQL ORDER BY FIELD与%

bd96500e110b49cbb3cd949968f18be7.png

I am trying to make an ORDER BY FIELD work with a wildcard, and have been unsuccessful:

SELECT positions.*,

departments.dept_name,

departments.dept_url,

divisions.dept_name AS div_name

FROM positions LEFT JOIN departments

ON positions.colleague_dept_code = departments.colleague_code

LEFT JOIN departments AS divisions

ON positions.colleague_div_code = divisions.colleague_code

WHERE colleague_id = '$colleague_id'

ORDER BY FIELD(positions.colleague_position_id, 'A%', 'F%', 'T%', 'S%', 'C%')

The colleague_position_id field has a text ID generated by our MIS system, and I'd like for positions starting with A to display first, F to display second, etc., etc.

Any help you could provide would be greatly appreciated.

Thanks!

解决方案

This should give you the most control over it:

order by

case left(positions.colleague_position_id, 1)

when 'A' then 1

when 'F' then 2

when 'T' then 3

when 'S' then 4

when 'C' then 5

else 6

end, positions.colleague_position_id

This is because you can send all non-matching values to the position you want (in this case at the end). The field() function will return 0 for non matching values and will put them at the top of the result set even before the ones starting with A.

Additionally, you can also order by positions.colleague_position_id as I did in the example, so that for many positions.colleague_position_id that start with the same letter they will still be in order.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值