任意排序来自MySql中的两个字段

时间:2013-05-23 18:49:24

标签: mysql

我很难做到。我需要能够以任意方式对查询结果进行排序。

以下是架构:

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

我该怎么做?

3 个答案:

答案 0 :(得分:4)

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

这将按两个条件排序。

答案 1 :(得分:0)

order by 
  CASE WHEN Quality = 'Medium' 
    and Sell_By < GETDATE() THEN 0 
    ELSE 1 END, 
  myOrder

或移动myOrder中的等效案例。顺便说一下,质量不应该是文本专栏。

答案 2 :(得分: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