我有一张球员桌。每个球员都有一个位置,可以是守门员,后卫,中场或前锋。我希望归还所有球员,首先是前锋,然后是中场,然后是后卫,然后是守门员。显然,如果我这样做:
SELECT *
FROM 'Player'
ORDER BY position
防守者将首先归还....
答案 0 :(得分:2)
SELECT *
FROM Player
ORDER BY find_in_set(position,'forward,midfielder,defender,goalkeeper')
答案 1 :(得分:2)
要么 -
使用FIELD()
作为suggested by @Bohemian,但请注意,这对于较大的表格不能很好地扩展(因为必须对每个记录的计算函数结果执行文件排序)。
将position
设为ENUM
:
ALTER TABLE Player
MODIFY position ENUM('forward','midfielder','defender','goalkeeper');
然后将相应地对现有查询的结果进行排序:
SELECT * FROM Player ORDER BY position;
这是因为,如The ENUM
Type所述:
排序
ENUM
值根据其索引号进行排序,这取决于列规范中列出枚举成员的顺序。
制作一张表来保持位置排序:
CREATE TABLE position_order (
position VARCHAR(15) PRIMARY KEY,
priority TINYINT UNSIGNED
);
INSERT INTO position_order
(position, priority)
VALUES
('forward' , 1),
('midfielder', 2),
('defender' , 3),
('goalkeeper', 4)
;
ALTER TABLE Player
ADD FOREIGN KEY (position) REFERENCES position_order (position);
然后,您可以通过加入表格并对新priority
列进行排序来对查询结果进行排序:
SELECT * FROM Player JOIN position_order USING (position) ORDER BY priority;
请注意,在决定采取何种方法之前,您可能希望阅读Chris Komlenic的文章8 Reasons Why MySQL's ENUM Data Type Is Evil。
答案 2 :(得分:0)
使用FIELD()
:
SELECT *
FROM Player
ORDER BY FIELD(position,'forward', 'midfielder', 'defender', 'goalkeeper')
答案 3 :(得分:-1)
您可以在ORDER BY子句中使用CASE语句。
SELECT *
FROM Player
ORDER BY CASE Position WHEN "forward" THEN 1
WHEN "defender" THEN 2
WHEN "midfielder" THEN 3
WHEN "goalkeeper" THEN 4 END ASC