简体   繁体   English

在不使用唯一列或键列的情况下,在两个SQL Server表(父列到子列)之间定义关系

[英]Define a relationship between two SQL Server tables (parent to child column) without the use of unique or key columns

I am trying to build a table which will hold the 'relationship' of a parent table and a child table. 我正在尝试构建一个表,该表将保存父表和子表的“关系”。 However each column in both tables are no keys or unique and there are duplicate values in each. 但是,两个表中的每列都没有键或唯一,每个列都有重复的值。

Example

Table A - Parent (Fact) 表A - 父母(事实)

**CartNumber**

Table B - Child 表B - 儿童

**CartNumber** not unique
CartValue

CartNumber from table A links to CartNumber in B. CartNumber从表格中的链接CartNumber在B.

I have tried to implement a foreign key with NOCHECK but of course that will not work since the child column is not a primary key or unique. 我试图用NOCHECK实现一个外键,但当然这不起作用,因为子列不是主键或唯一。 Bear in mind, I am ONLY trying to define that there is a link between the two columns/tables. 请记住,我只是试图定义两个列/表之间存在链接。 Is there any way to define a 'loose' relationship between the two columns? 有没有办法在两列之间定义“松散”关系? Preferably a method where I can reference the sys views or information schema to extract this information 优选地,我可以引用sys视图或信息模式来提取该信息的方法

To be honest: This design smells and - if possible - you should think about changing this... 说实话:这个设计闻起来 - 如果可能的话 - 你应该考虑改变这个......

There is no chance to define a FOREIGN KEY CONSTRAINT on non-unique columns the way you describe it. 没有机会按照您描述的方式在非唯一列上定义FOREIGN KEY CONSTRAINT

But: To define a JOIN there is no need for a FK! 但是: 要定义JOIN ,不需要FK!

My suggestion: 我的建议:

Create a VIEW like this: 像这样创建一个VIEW

CREATE VIEW dbo.MyView
AS
SELECT a.Col1,a.Col2,...
      ,b.Col1,b.Col2,...
FROM TableA AS a
[INNER/LEFT/RIGHT/FULL OUTER] JOIN TableB AS b ON a.RelField=b.RelField;

With such a VIEW you will get the data joined on this non-unique information. 使用这样的VIEW,您将获得有关此非唯一信息的数据。

UPDATE UPDATE

Taken form your comment: 采取你的评论:

the end goal is just to provide an external web service with information that says Column A from Table A is used to join onto Column B from Table B 最终目标只是为外部Web服务提供信息,表示表A中的A列用于连接到表B中的B列

You can create a meta-table like this: 您可以创建这样的元表:

CREATE TABLE dbo.ColumnReference
(
 ColumnReferenceID INT IDENTITY
,TABLE_NAME_A VARCHAR(255) NOT NULL
,COLUMN_NAME_A VARCHAR(255) NOT NULL
,TABLE_NAME_B VARCHAR(255) NOT NULL
,COLUMN_NAME_B VARCHAR(255) NOT NULL
);
--inlcude SCHEMA if needed...

In this case you can maintain these relations in your own structure..., you might even add details, rules, what ever... 在这种情况下,您可以在自己的结构中维护这些关系......,您甚至可以添加细节,规则,什么......

The web service will call this directly. Web服务将直接调用它。 You might use a VIEW to combine existing relations (defined as FK CONSTRAINT ) with your own meta table (simply with UNION ALL ). 您可以使用VIEW将现有关系(定义为FK CONSTRAINT )与您自己的元表(仅使用UNION ALL )组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM