MySQL组与另一列的排序/优先级

前端之家收集整理的这篇文章主要介绍了MySQL组与另一列的排序/优先级前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我已经看过这两个问题了:

> Grouping by Column with Dependence on another Column
> MySQL GROUP BY with preference

但是它们都使用聚合函数MAX来获得最高值或填充值,这对我的情况不起作用.

出于这个问题的目的,我简化了我的情况.这是我目前的数据:

我想获得每条路线的操作符名称,但是关于旅行方向(即订购或“优先”价值).这是我的伪代码

  1. if(`direction` = 'west' AND `operatorName` != '') then select `operatorName`
  2. else if(`direction` = 'north' AND `operatorName` != '') then select `operatorName`
  3. else if(`direction` = 'south' AND `operatorName` != '') then select `operatorName`
  4. else if(`direction` = 'east' AND `operatorName` != '') then select `operatorName`

我当前的SQL查询是:

  1. SELECT route,operatorName
  2. FROM test
  3. GROUP BY route

这给了我分组,但我的目的是错误的运算符:

  1. route | operatorName
  2. --------------------
  3. 95 | James
  4. 96 | Mark
  5. 97 | Justin

我尝试过应用ORDER BY子句但GROUP BY优先.我想要的结果是什么:

  1. route | operatorName
  2. --------------------
  3. 95 | Richard
  4. 96 | Andrew
  5. 97 | Justin

我不能在这里做MAX(),因为“north”按字母顺序排在“south”之前.在应用GROUP BY子句之前,如何明确说明我的偏好/排序?

另请注意,空字符串不是首选.

请注意,这是一个简化的示例.实际查询选择了更多字段并与其他三个表连接,但查询中没有聚合函数.

最佳答案
你可以使用那个MAX例子,你只需要“伪造它”.见:http://sqlfiddle.com/#!2/58688/5

  1. SELECT *
  2. FROM test
  3. JOIN (SELECT 'west' AS direction,4 AS weight
  4. UNION
  5. SELECT 'north',3
  6. UNION
  7. SELECT 'south',2
  8. UNION
  9. SELECT 'east',1) AS priority
  10. ON priority.direction = test.direction
  11. JOIN (
  12. SELECT route,MAX(weight) AS weight
  13. FROM test
  14. JOIN (SELECT 'west' AS direction,4 AS weight
  15. UNION
  16. SELECT 'north',3
  17. UNION
  18. SELECT 'south',2
  19. UNION
  20. SELECT 'east',1) AS priority
  21. ON priority.direction = test.direction
  22. GROUP BY route
  23. ) AS t1
  24. ON t1.route = test.route
  25. AND t1.weight = priority.weight

猜你在找的MySQL相关文章