具有次级子排序的OrderBy

时间:2019-06-12 23:31:43

标签: mysql

我需要建立一个查询,该查询按优先级进行匹配;但是,在某些情况下,如果我有重复的产品,我希望在初始匹配时将其以最高优先级进行分组。不知道这在MySQL中是否可行,或者我是否需要在PHP或JS中进行后期处理。

+-------+----------+---------+
| order_id | Priority | Product |
+-------+----------+---------+
| 12345 |        1 |  334455 |
| 12345 |        1 |  212121 |
| 12355 |        2 |  666666 |
| 12356 |        3 |  212121 |
| 12360 |        4 |  777777 |
+-------+----------+---------+

我尝试过的东西当然失败了。我尝试使用“ FIELD()”执行相同的操作。

SELECT Order_id, Priority, Product FROM Products ORDER BY Priority ASC, Product

所需结果

+-------+----------+---------+
| Order_id | Priority | Product |
+-------+----------+---------+
| 12345 |        1 |  334455 |
| 12345 |        1 |  212121 |
| 12356 |        3 |  212121 |
| 12355 |        2 |  666666 |
| 12360 |        4 |  777777 |
+-------+----------+---------+

2 个答案:

答案 0 :(得分:0)

类似这样的事情应该可以解决:

select order_id, Priority, Product,
    (select min(Priority) from Products p1 where p.product = p1.product) as MinPrior
from Products p
order by MinPrior asc, Product asc, Priority asc;

我知道,它与“所需结果”中的不完全相同,但是如果我正确理解了问题,它将完成所需的任务。

我希望能对您有所帮助。

答案 1 :(得分:0)

已编辑

我删除了我的第一个建议,并发布了一个查询,使我可以确定结果:

SELECT v.Order,v.Priority,v.Product,
       CASE WHEN priority < b_prio OR priority > b_prio AND product=b_prod THEN 1 
            WHEN priority=1 AND  product=b_prod THEN 0 
            WHEN priority <> 1 AND  product=b_prod THEN 2 END custom_rank FROM
     (SELECT a.*,
             IFNULL(b.order,a.order) b_order,
             IFNULL(b.product,a.product) b_prod,
             IFNULL(b.priority,a.priority) b_prio
        FROM products a LEFT JOIN products b 
          ON a.product=b.product AND a.priority <> b.priority) v 
ORDER BY custom_rank, priority;

因此,我们的想法是创建一个自定义排名。上面的查询将产生以下内容: enter image description here

如果满足条件LEFT JOIN,我在products表上做了一个自b_prio来切换ON a.product=b.product AND a.priority <> b.priority中的优先级。 IFNULL将从products a中获取价值。然后从外部查询中,根据CASE表达式创建了一个自定义排名。这样,我执行ORDER BY custom_rank, priority;并可以获得您想要的结果。