返回顶部

收藏

sql中order by(true or false) 类似 group by 的方式

更多
例子1    排序boolean类型
CREATE TABLE `tab_b` (
  `field` varchar(255) default NULL,
  `id` int(11) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `tab_b` VALUES ('1', 'ture');
INSERT INTO `tab_b` VALUES ('2', 'ture');
INSERT INTO `tab_b` VALUES ('3', 'false');
INSERT INTO `tab_b` VALUES ('4', 'false');

SELECT * from TAB_B ORDER BY  field='true' desc

注意:ORDER  by 后接的字段如果是boolean属性,则false比ture ‘大’!!!!!

########################################################

DROP TABLE IF EXISTS `tab_a`;
CREATE TABLE `tab_a` (
  `id` int(11) NOT NULL,
  `field3` int(11) default NULL,
  `field2` int(11) default NULL,
  `field1` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `tab_a` VALUES ('1', '1', '1', '1');
INSERT INTO `tab_a` VALUES ('2', '2', '2', '2');
INSERT INTO `tab_a` VALUES ('3', '3', '3', null);
INSERT INTO `tab_a` VALUES ('4', '4', null, null);
INSERT INTO `tab_a` VALUES ('5', '5', '5', null);
INSERT INTO `tab_a` VALUES ('6', null, null, null);
INSERT INTO `tab_a` VALUES ('7', null, null, null);
INSERT INTO `tab_a` VALUES ('8', '8', null, null);
SELECT  * FROM TAB_A  ORDER BY 
  field1='' desc , field1 asc, 
  field2='' desc , field2 asc,
  field3='' desc  ,field3 asc 

            此处field1='' 可以看成boolean排序  desc 排序,field1=''为真的排在下面(因为看上面"注意"),否则排在上面(即field1!='');
                  而后面的field1 asc相当于排序field1!=''数据,依次排序field2,field3..........

标签:sql

收藏

0人收藏

支持

0

反对

0

发表评论