Postgresql

儲存邏輯表達式的推薦方式

  • November 29, 2019

說,我有以下 SQL 表:

| ID | GameId   | PlanId | MinAgeLimit | Amount |
|:--------------|--------|-------------|-------:|
| 1  | Cricket  |   P1   |   10        |   500  |
| 2  | Cricket  |   P2   |   15        |  1000  |
| 3  | Football |   P1   |   10        |   750  |
| 4  | Football |   P2   |   20        |  1000  |
| 5  | Football |   P3   |   22        |  2000  |
| 6  | Chess    |   P2   |   20        |   800  |

現在,我可以對不同的“ReferrerId”有一些邏輯表達式,例如:

如果Referrer=ABC,則不顯示項目所在的位置PlanId=P2

如果Referrer=PQR,則僅顯示 的項目GameId=Cricket

如果Referrer=XYZ, 顯示項目在哪裡(GameID=Cricket OR GameID=Chess) AND MinAgeLimit>10 AND AMOUNT>500

儲存這些自定義規則的推薦方法是什麼?

PS:我不想在我的 Java 程序中硬編碼這些規則,因為我計劃進一步提供一個介面,Referrer 可以通過自助服務門戶更新這些規則。

這可以作為一組表來實現。針對每個源列的每個邏輯運算符將有一列。由於這會導致很多組合,我建議只部署當時需要的列。該設計允許稍後包含新列。

決策表:

Referrer
PlanIdNotEqual
GameIdIn              -- this is just a flag to say whether this condition applies to this referrer
MinAgeLimitGreaterThan
AmountGreaterThan
...
further columns to meet additional conditions

由於一個推薦人的條件有多個 GameId 值,因此它得到一個單獨的表:

DecisionGameIdIn
   Referrer
   GameId

然後查詢變為(在偽 SQL 中)

select
 <columns>
from Game
inner join Decision
on  (Decision.PlanIdNotEqual is NULL 
    or Decision.PlanIdNotEqual <> Game.PlanId)
and (Decision.GameIdIn is NULL 
    or Game.GameId in (select GameId from DecisionGameIdIn where Referrer = <current value>))
and (Decision.MinAgeLimitGreaterThan is NULL 
    or Game.MinAgeLimit > Decision.MinAgeLimitGreaterThan)
and (Decision.AmountGreaterThan is NULL 
    or Game.Amount > Decision.AmountGreaterThan)
... continue for further conditions
where Decision.Referrer = <the current value>

這可能會迅速失控。使 Decision 的列與查詢邏輯保持一致是一個問題。組合爆炸是另一回事。過多的布爾條件可能會壓倒任何導致表掃描的索引策略。

恕我直言,最簡單的方法是向表中添加一個Conditions欄位Referrer's

CREATE TABLE Referrer 
(
   ReferrerID  int  PRIMARY KEY,
   ....
   ....
   Conditions  nvarchar(max)
);

顯然,您需要某種動態的 STORED PROCEDURE 或 FUNCTION 來從表中檢索資訊。

CREATE PROCEDURE dbo.SelectReferrerInfo (@ReferrerId int)
AS
   DECLARE @cmd nvarchar(MAX);

   SET @cmd = 'SELECT
                   ReferrerId,
                   ...,
                   ...,
                   ...
               FROM
                   dbo.YourTable'
               + CASE WHEN Conditions IS NOT NULL
                      THEN ' WHERE ' + Conditions
                      END 
               + ' WHERE ReferrerId = ' + CAST(@ReferrerId as nvarchar(100))
   FROM
       ReferrerTable
   WHERE
       ReferrerID = @ReferrerId;

   EXEC sys.sp_executesql @cmd;

注意:我使用了 SQL Server 語法。

引用自:https://dba.stackexchange.com/questions/223097