简体   繁体   English

如何为SQL中的列组合赋予唯一约束,而不考虑Order

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

I have a two tables. 我有两张桌子。 First One is the product table that hold the Data and the second one holds the Parent Child relationship. 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.)

How to add a unique constraint for (Fk_ProductId, ProductId) so that combination of Fk_Productid and ProductId cannot be added. 如何为(Fk_ProductId,ProductId)添加唯一约束,以便无法添加Fk_Productid和ProductId的组合。

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

i have already added a constraint as below. 我已经添加了一个约束如下。

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

Also i am planning to prevent any illegal entry where it will cause a loop. 此外,我打算防止任何非法进入,它会导致循环。 like below. 如下。

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

Any product(P1) can be accessory of any other product(P2) as long as the accessory product P1 is not a parent product, grand parent product or anywhere in its Parents line which will cause a circular loop. 任何产品(P1)可以是任何其他产品(P2)的附件,只要附件产品P1不是母产品,祖母产品或其父产品系列中的任何地方将导致循环回路。

You can do this by using computed columns: 您可以使用计算列来执行此操作:

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