如何将数据= 0与数据= 0分开,然后对数据= 0 ASC排序,最后将数据= 0排序。
CREATE TABLE `fruit` (
`item` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`price` int(6) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- Dumping data for table `fruit`
INSERT INTO `fruit` (`item`, `type`, `price`) VALUES
('Apple', 'Grade A', 10),
('Apple', 'Grade B', 8),
('Banana', 'Grade A', 15),
('Banana', 'Grade B', 0),
('Banana', 'Grade C', 8),
('Mango', 'Grade A', 0),
('Mango', 'Grade B', 12);
-- Indexes for dumped tables
-- Indexes for table `fruit`
ALTER TABLE `fruit`
ADD PRIMARY KEY (`item`,`type`) USING BTREE;
我尝试排序:
SELECT * FROM `fruit`
ORDER BY price DESC, item ASC
结果变为:
('Banana', 'Grade A', 15),
('Mango', 'Grade B', 12),
('Apple', 'Grade A', 10),
('Apple', 'Grade B', 8),
('Banana', 'Grade C', 8),
('Banana', 'Grade B', 0),
('Mango', 'Grade A', 0),
Actuall我只想将价格= 0推到最后,那些不是= 0的价格将跟随主要指数
我想要这样的结果:
('Apple', 'Grade A', 10),
('Apple', 'Grade B', 8),
('Banana', 'Grade A', 15),
('Banana', 'Grade C', 8),
('Mango', 'Grade B', 12),
('Banana', 'Grade B', 0),
('Mango', 'Grade A', 0),
我该怎么做?
答案 0 :(得分:2)
您需要使用条件order by
。这是SQL fiddle
答案 1 :(得分:1)
尝试此代码
SELECT * FROM `fruit`
ORDER BY price=0,item asc
答案 2 :(得分:-2)
尝试一下
SELECT * FROM `fruit`
ORDER BY if(price=0,0,1) DESC,price DESC, item ASC