我在SQL Server中有一个表Authors
,其中Author_ID
为主键。
Authors
表格结构
Author_ID | Author_Name
----------------------------
677 | Nuno Vasconcelos
1359 | Peng Shi
6242 | Z. Q. Shi
... | ...
... | ...
我有另一个表CoAuthors
,其中CoAuthor_ID
为主键,Author_ID
为外键。
CoAuthors
表格结构
CoAuthor_ID | CoAuthor_Name | Author_ID
---------------------------------------
47 | Jim Bezdek | NULL
111 | Vishal Gupta | NULL
318 | Muaz A. Niazi | NULL
... | ... | ...
... | ... | ...
我有另一个Author-CoAuthor映射表Yearly_Author_CoAuthors
:
Author_ID | CoAuthor_ID | Year
------------------------------
677 | 901706 | 2005
677 | 838459 | 2007
677 | 901706 | 2007
... | ... | ...
... | ... | ...
现在我必须在来自CoAuthors
表的Authors
表中插入外键。问题是,对于Author_ID
,我可能有CoAuthor_ID
的多个值,例如执行此查询:
SELECT
Author_ID, CoAuthor_ID, Year
FROM
Yearly_Author_CoAuthors
WHERE
CoAuthor = 901706
ORDER BY
Author_ID, Year, CoAuthor_ID
我得到了这个输出:
Author_ID | CoAuthor_ID | Year
------------------------------
677 | 901706 | 2005
677 | 901706 | 2007
677 | 901706 | 2009
1683703 | 901706 | 2012
显示CoAuthor_ID = 901706
有两个DISTINCT Author_ID
,所以这里:
如何在Author_ID
表中插入CoAuthors
作为外键约束?
答案 0 :(得分:0)
只要Author_ID在authors表中是唯一的,作者和共同作者之间潜在的多对多关系就不会阻止外键约束。只需这样做:
ALTER TABLE CoAuthors
ADD CONSTRAINT FK_Authors_Author_ID FOREIGN KEY (CoAuthor_ID)
REFERENCES Authors (Author_ID)
答案 1 :(得分:0)
查看示例Yearly_Author_CoAuthors选择查询,您必须输入重复值才能返回它们。
制作Author_ID& CoAuthor_ID复合主键(不含年份)或在这两列中添加唯一索引。
编辑: 如果你在Yearly_Author_CoAuthors.Author_ID和Yearly_Author_CoAuthors.CoAuthor_ID上没有外键,那么我首先建议你在user3481891的答案中调整脚本,将它们添加到该表中。 然后,我不明白为什么你不能查询你已有的东西。以下是一些例子(未经测试的我害怕,如果他们不工作,请告诉我):
-- to get list of who a CoAuthor has worked with and when
select a.Author_Name,
ca.CoAuthor_Name,
[Year]
from Authors a inner join
Yearly_Author_CoAuthors yac on a.Author_ID = yac.Author_ID inner join
CoAuthors ca on yac.CoAuthor_ID = ca.CoAuthor_ID
where yac.CoAuthor = 901706
-- to get a list of first occasions when a CoAuthor has worked with each Author
select a.Author_Name,
ca.CoAuthor_Name,
min([Year]) as FirstCollaborationDate
from Authors a inner join
Yearly_Author_CoAuthors yac on a.Author_ID = yac.Author_ID inner join
CoAuthors ca on yac.CoAuthor_ID = ca.CoAuthor_ID
where yac.CoAuthor = 901706
group by a.Author_Name,
ca.CoAuthor_Name
order by min([Year])