Home > Database > Mysql Tutorial > sql中order by(true or false) 类似 group by 的方式

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 14:57:57
Original
1759 people have browsed it

适用场景: 如表tab_a 有三个字段, 如果field1非空则按升序排列, 如果field1是空再排field2, 如果 field2非空升序排列, 如果field2是空再排field3, 如果field3非空则升序排列, 如果field3是空。。。。。。。。 或者 你想查询field1x的按照升(降)序排

适用场景:
如表tab_a 有三个字段,
如果field1非空则按升序排列,
如果field1是空再排field2,
如果 field2非空升序排列,
如果field2是空再排field3,
如果field3非空则升序排列,
如果field3是空。。。。。。。。

或者
你想查询field1>x 的按照升(降)序排列,
例子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..........
Copy after login
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
sql file
From 1970-01-01 08:00:00
0
0
0
php - Overhead of prepare vs sql?
From 1970-01-01 08:00:00
0
0
0
Print sql statement
From 1970-01-01 08:00:00
0
0
0
Pass array to SQL insert query using PHP
From 1970-01-01 08:00:00
0
0
0
sql optimization or
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template