根据表配置应用不同的排序条件

时间:2011-08-12 06:56:48

标签: mysql

我有一个mysql表“Routing”,其中包含4个字段:Id,Rcost,Rpriority,Rmargin。我们需要设计一个路由引擎,它将根据以下标准获取路由: 1.最低成本 2.最高优先级 3.最高利润率

根据以下规则,将在一个差异表中列出不同的路由机制及其优先级.1 =>最高优先级; 3 =>最低优先级; 0 =>不适用。

如果给定的算法返回多个路由,这些选择的路由将应用于下一个算法,如果再次返回多个路由,则这些返回的路由将再次应用于下一个算法,直到返回单个路由或没有算法为止剩下。如果没有剩下算法,那么将使用列表中的第一个返回路由。

以下是表格内容:

CREATE TABLE Routing (
        Id INT(10) NOT NULL auto_increment,
        Prefix VARCHAR(30) NOT NULL,
        Route INT(10) NOT NULL,
        Cost FLOAT NULL DEFAULT 0,
        Priority INT(10) NULL DEFAULT 0,
        ProfitMargin INT(10),
        Quality INT(10),
        PRIMARY KEY(Id)
);

表格数据:

INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (10, 20, 8, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (10, 20, 8, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (5, 18, 10, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (5, 18, 8, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (5, 19, 10, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (10, 20, 8, 4);
INSERT INTO Routing (Cost, Priority, ProfitMargin, Quality) VALUES (10, 20, 8, 4);
INSERT INTO Routing (Cost, ProfitMargin, Quality) VALUES (5, 10, 4);

根据上述规则,另一张表载有关于分拣机制的应用优先级及其适用性的信息。

其他表:

DROP TABLE IF EXISTS RoutingCriteria;
CREATE TABLE RoutingCriteria (
                Id INT(10) NOT NULL auto_increment,
                Cost TINYINT,
                Priority TINYINT,
                Quality TINYINT,
                ProfitMargin    INT(4),
                PRIMARY KEY(Id)
);

表格数据:

insert into RoutingCriteria (Cost, Priority, Quality, ProfitMargin) VALUES(1, 2, 3, 4);
insert into RoutingCriteria (Cost, Priority, Quality, ProfitMargin) VALUES(4, 1, 3, 2);
insert into RoutingCriteria (Cost, Priority, Quality, ProfitMargin) VALUES(0, 2, 3, 0);
insert into RoutingCriteria (Cost, Priority, Quality, ProfitMargin) VALUES(1, 0, 3, 4);

如果我们使用不同的routeCriteria值,我们需要获取路线。

1 个答案:

答案 0 :(得分:0)

鉴于此信息,我可以提出建议:

SELECT * 
  FROM Routing 
 WHERE Priority > 0         -- excluding Not applicable
 ORDEY BY Cost ASC          -- Least Cost
        , Priority ASC      -- 1=> Highest; 3=> Lowest
        , ProfitMargin DESC -- Highest profitMargin
 LIMIT 1                    -- return only 1 result, i.e the first/best