簡體   English   中英

如何為SQL中的列組合賦予唯一約束,而不考慮Order

[英]How to give a unique constraint to a combination of columns in SQL irrespective of Order

我有兩張桌子。 First One是包含Data的產品表,第二個包含Parent Child關系。

ProductTable
===================
PkId Manufacturer Model ...
1      A            A1
2      B            B1
3      C            C1

JoinIng Table for Parent Child relationship (accessories)

Accessories
=============
PkAccessoryId  Fk_ProductId(Child)  ProductId(Parent)
---------------------------------------------------------
1                      2                1              (A has B As accessory)
2                      1                2              (B has A as accessory)  --(//this record is an invalid entry due to the missing constraint and need to prevent this.)

如何為(Fk_ProductId,ProductId)添加唯一約束,以便無法添加Fk_Productid和ProductId的組合。

Example: Invalid case as this will make a loop of accessory
         1,  2
         2   1 

我已經添加了一個約束如下。

ALTER TABLE Tx_ProductAccessories
  ADD CONSTRAINT UNI_CONS_Fk_ProductId_ProductId UNIQUE(Fk_ProductId, ProductId);

此外,我打算防止任何非法進入,它會導致循環。 如下。

 A-A   (Read product A has product A as accessory )
 A-B-A
 A-B-C-A
 A-B-C-B
 ...

任何產品(P1)可以是任何其他產品(P2)的附件,只要附件產品P1不是母產品,祖母產品或其父產品系列中的任何地方將導致循環回路。

您可以使用計算列來執行此操作:

alter table Tx_ProductAccessories
    add least_productId as (case when Fk_ProductId < ProductId
                                 then Fk_ProductId else ProductId end);

alter table Tx_ProductAccessories
    add greatest_productId as (case when Fk_ProductId < ProductId
                                    then ProductId else Fk_ProductId end);

alter table Tx_ProductAccessories
    add constraint uni_fkProductId_ProductId unique(least_productId, greatest_ProductId);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM