【问题标题】:How to create 2 to N associations in SQL如何在 SQL 中创建 2 对 N 关联
【发布时间】:2017-01-31 08:15:02
【问题描述】:

以前我的表会一对一地关联记录,因此我只是将关联记录模型的 ID 存储在其合作伙伴记录中。

我更新了我的模型以允许这些记录与许多其他记录相关联,只要它们在多个列中具有相同的值。我在我的数据库中添加了一个新表,该表将为每组关联记录存储一个唯一的分组 ID。我还在我的模型中添加了一个列,以便关联的记录可以保存对其分组 ID 的引用。

我在这里有两张桌子在玩。我们可以称之为“记录”的主表,然后是“记录关联”表。

模型真的不重要,除了:

记录 PK指导 | {然后是一些字段,在我们的例子中是 address1、address2、city、zip 等} | FK RecordAssociationId guid

唱片协会 PK指导

我将如何填充关联表并更新记录表。

【问题讨论】:

  • 2 到 N?这应该是一个有趣的场景。用例是什么?你能提供一个简化版的模型吗?
  • slicedbread 的同事在这里:我们基本上有一个从 0:1 到 0:many 的自引用表。我们创建了一个仅包含审计信息和主键的关联表。然后我们将事物记录与主表相关联。创建这个额外的表并不是特别需要,但它使我们的应用层中的事情变得更加清晰。但是 2:many 出现在我们不想创建关联记录或在主表上设置 FK 时,它实际上与任何东西都不相关。 IE。我们不希望 1 人一组。

标签: sql sql-server


【解决方案1】:

这是我们提出的解决方案:

--Start by setting up a temp table so we can do joins
declare @recordAssociationTemp table
(
UniqueId VARCHAR(500) NOT NULL,
NewAssociationId uniqueidentifier NULL,
CreatedBy uniqueidentifier NOT NULL
);

--Select the columns we want to associate on by making a unique ID out of the common fields
with temp as
(
select isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')+ isnull(a.CreatedBy,'') as UniqueId,
a.CreatedBy,
ROW_NUMBER() over (partition by isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')
+ isnull(a.CreatedBy,'') order by a.CreatedBy) as RowNum
from dbo.[Record] as a inner join DGSystem as dgs on a.SystemId = dgs.Id
)
--ROW_NUMBER() helps us assign an increasing ID to each duplicate row so we can avoid making associations for records that only have a single entry 
insert @recordAssociationTemp (UniqueId, CreatedBy)
select distinct UniqueId, CreatedBy
from temp
where RowNum > 1; -- > 1 allows us to skip over records that don't have any associations 

update @recordAssociationTemp
set NewAssociationId = NEWID();

--this is where we add new records to our association table with the generated unique IDs and some accociated audit data
insert into dbo.RecordAssociation
(Id, CreatedBy, CreatedDateTime, ModifiedBy, ModifiedDateTime)
select NewAssociationId, CreatedBy, SYSDATETIME(), CreatedBy, SYSDATETIME()
from @recordAssociationTemp;

--finally, we join our temp table to apply our new IDs to the record table
update a
set a.RecordAssociationId = aat.NewAssociationId
from dbo.[Record] as a inner join DGSystem as dgs on a.SystemId = dgs.Id
inner join @recordAssociationTemp as aat on isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')
+ isnull(a.CreatedBy,'') = aat.UniqueId;

【讨论】:

  • 这是您问题的答案还是延伸?
  • 这是对我自己问题的回答。我现在说得更清楚了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 2021-02-01
相关资源
最近更新 更多