我正在尝试使用通配符使 ORDER BY FIELD 工作,但没有成功:
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%')
colleague_position_id 字段有一个由我们的 MIS 系统生成的文本 ID,我希望以 A 开头的职位首先显示,F 显示第二,依此类推。
如果您能提供任何帮助,我们将不胜感激。
谢谢!
最佳答案
这应该给你最大的控制权:
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
这是因为您可以将所有不匹配的值发送到您想要的位置(在本例中为末尾)。 field() 函数将为不匹配的值返回 0 并将它们放在结果集的顶部,甚至在以 A 开头的值之前>.
此外,您还可以像我在示例中所做的那样按 positions.colleague_position_id 进行排序,这样对于许多以相同字母开头的 positions.colleague_position_id,它们仍然会井井有条。
关于MySQL ORDER BY FIELD with %,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9917829/