原创

MySQL-代码-order by3个字段2种维度排序

需求:
1、顺序按置顶,多个置顶则按更新的时间降序
2、然后按发布时间降序排

-- 特别注意 is_up_new 如果有null值,也不能使用ifnull(is_up_new,0),
SELECT * from test_ss ORDER BY is_up_new + update_time desc , fabushijian desc
-- null值非常重要,没有还要设置出来
SELECT * from test_ss ORDER BY if(is_up_new = 1,1,null) + update_time desc , fabushijian desc;
-- null值非常重要,没有还要设置出来
SELECT * from test_ss ORDER BY if(is_up_new2 = '是',1,null) + update_time desc , fabushijian desc;
-- 保险点,改成这个
SELECT * from test_ss ORDER BY if(is_up_new2 = '是',2000000000 +UNIX_TIMESTAMP(update_time) ,UNIX_TIMESTAMP(fabushijian)) desc;





DROP TABLE IF EXISTS `test_ss`;
CREATE TABLE `test_ss` (
`id` int(11) NOT NULL,
`fabushijian` datetime(0) DEFAULT NULL,
`update_time` datetime(0) DEFAULT NULL,
`is_up_new` int(2) DEFAULT 0,
`is_up_new2` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`notice_title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;



INSERT INTO `test_ss` VALUES (1, '2023-10-25 09:13:13', '2023-11-25 09:13:13', NULL, '否', '111');
INSERT INTO `test_ss` VALUES (2, '2023-09-26 09:13:33', '2023-09-26 09:13:33', 1, '是', '222');
INSERT INTO `test_ss` VALUES (3, '2023-09-28 09:13:55', '2023-11-28 09:13:55', 1, '是', '333');
INSERT INTO `test_ss` VALUES (4, '2023-10-24 09:14:09', '2023-08-24 09:14:09', NULL, '否', '4444');


正文到此结束
本文目录