0

我有一个困难的事情要做。我需要能够以任意方式对查询结果进行排序。

这是架构:

CREATE  TABLE `Wines` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `Vinyard` VARCHAR(45) NULL ,
  `Quality` VARCHAR(45) NULL ,
  `Sell_By` DATE NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Draper', 'High', '2012-03-22');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Draper', 'Medium', '2014-07-16');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Draper', 'Medium', '2012-01-01');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Becks', 'High', '2014-07-16');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Becks', 'Ultra', '2013-02-02');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Stevens', 'Crap', '2014-08-16');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Stevens', 'Medium', '2014-01-01');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Stevens', 'Low', '2013-09-13');
INSERT INTO `Wines` (`Vinyard`, `Quality`, `Sell_By`) VALUES ('Miller', 'Low', '2014-01-01');

现在我知道我可以得到一种简单的质量(不是按字母顺序排列的),如下所示:

 SELECT *,
CASE Quality
WHEN 'Ultra' THEN 1
WHEN 'High' THEN 2
WHEN 'Medium' THEN 3
WHEN 'Low' THEN 4
WHEN 'Crap' THEN 5
ELSE 6
END AS myORDER
FROM Wines
ORDER BY myOrder

那给了我

ID  Vinyard Quality Sell_By myORDER
5   Becks   Ultra   2013-02-02  1
1   Draper  High    2012-03-22  2
4   Becks   High    2014-07-16  2
2   Draper  Medium  2014-07-16  3
3   Draper  Medium  2012-01-01  3
7   Stevens Medium  2014-01-01  3
8   Stevens Low 2013-09-13  4
9   Miller  Low 2014-01-01  4
6   Stevens Crap    2014-08-16  5

好的,到目前为止一切都很好。现在皱纹。

我需要移动中等品质的葡萄酒 ,并且只移动 销售日期已过的中等品质的葡萄酒。所以结果是

ID  Vinyard Quality Sell_By
5   Becks   Ultra   2013-02-02
1   Draper  High    2012-03-22
4   Becks   High    2014-07-16
2   Draper  Medium  2014-07-16
7   Stevens Medium  2014-01-01
8   Stevens Low 2013-09-13
9   Miller  Low 2014-01-01
6   Stevens Crap    2014-08-16
3   Draper  Medium  2012-01-01  <--Notice this one moved

我怎样才能做到这一点?

4

3 回答 3

4
ORDER BY Quality = 'Medium' AND Sell_By < CURDATE(), myOrder

这将按两个条件排序。

于 2013-05-23T18:55:11.023 回答
0
order by 
  CASE WHEN Quality = 'Medium' 
    and Sell_By < GETDATE() THEN 0 
    ELSE 1 END, 
  myOrder

或在 myOrder 中移动等效的大小写。顺便说一句,质量不应该是一个文本列。

于 2013-05-23T18:55:10.747 回答
0

我建议以下查询:

SELECT *,
CASE Quality
WHEN 'Ultra' THEN 1
WHEN 'High' THEN 2
WHEN 'Medium' THEN 3
WHEN 'Low' THEN 4
WHEN 'Crap' THEN 5
ELSE 6
END AS myOrder,
IF(`Quality`='Medium' AND `Sell_By`<NOW(),`Sell_By`,NULL) as `med_sell_by`
FROM Wines
ORDER BY ISNULL(`med_sell_by`) DESC,`med_sell_by` ASC, myOrder ASC;

这将返回一个附加列,如果它quality是“中等”并且sell_by已经过去,则包含sell_by排序到底部的日期。如果不满足这些条件,则附加字段将为 NULL 并排序到顶部。

SQLFIDDLE

于 2013-05-23T18:59:52.630 回答