MySQL ORDER BY FIELD with %

柔情痞子 提交于 2019-12-23 20:35:53

问题


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!


回答1:


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.




回答2:


How about removing the WildCard?

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

See Source: ORDER BY SPECIFIC VALUE



来源:https://stackoverflow.com/questions/9917829/mysql-order-by-field-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!