mysql按具有两个不同值记录对行进行排序

ru9i0ody  于 2022-10-31  发布在  Mysql
关注(0)|答案(1)|浏览(124)

我有值等于1或2的记录我希望按此记录对行进行如下排序

1
2
1
2
1
2
1

我怎样才能只按DESC或ASC的订单来做这个订单?
注意:有主键id,有创建日期

CREATE TABLE `users` (
    `uid` INT(11) NOT NULL AUTO_INCREMENT,
    `phone_number` VARCHAR(16) NOT NULL,
    `password` VARCHAR(100) NOT NULL,
    `first_name` VARCHAR(100) NOT NULL,
    `last_name` VARCHAR(100) NOT NULL,
    `sex` TINYINT(4) NOT NULL, << this will have only 1 or 2
    `created_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `account_status` TINYINT(1) NOT NULL, 
    PRIMARY KEY (`uid`)
);
xkrw2x1b

xkrw2x1b1#

请尝试以下查询:

SELECT t.*
FROM (
  SELECT STRAIGHT_JOIN  uid, first_name , 
    @y:=IF(@sex=sex,@y+1,1) AS rnk, @sex:=sex AS sex
  FROM (SELECT @sex:=NULL) AS x
  JOIN users
  ORDER BY sex, uid DESC
) AS t
ORDER BY rnk ASC, sex ASC;

相关问题