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:
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 return0for non matching values and will put them at the top of the result set even before the ones starting withA.Additionally, you can also order by
positions.colleague_position_idas I did in the example, so that for manypositions.colleague_position_idthat start with the same letter they will still be in order.