mysql – 根据列值显示备用结果

我有一张包含以下数据的表格

id      name            gender(Enum : Male,Female)
1       John Doe        Male
2       Panther Jow     Male
3       Faran Aktar     Female
4       Rohan Fusi      Male
5       Soham Das       Female
6       Rohit Dutta     Female
7       Sozi Petacus    Male
8       Tuhin Dtui      Male

我想要一个SQL查询,其中结果应该查看一个男性和一个女性然后再一个男性和一个女性连续.如果在男性或女性结果之后如果无法获得下一个女性或男性数据,那么所有结果都会显示出来.像这样

   id      name            gender(Enum : Male,Female)
    1       John Doe        Male
    3       Faran Aktar     Female
    2       Panther Jow     Male
    5       Soham Das       Female
    4       Rohan Fusi      Male
    6       Rohit Dutta     Female
    7       Sozi Petacus    Male 
    8       Tuhin Dtui      Male

如果有人能帮助我,那么我会很高兴他/她.
提前致谢

最佳答案 你可以试试这个:

SELECT rnk, name ,gender
FROM (
  SELECT STRAIGHT_JOIN id, name, @y:=IF(@gender=gender,@y+1,1) AS rnk, @gender:=gender AS gender
  FROM (SELECT @gender:=NULL) AS x
  JOIN test
  ORDER BY gender, name DESC
) AS t
ORDER BY rnk ASC, gender DESC;

FIDDLE DEMO

点赞