创建/添加外键访问

时间:2014-02-25 18:03:21

标签: sql ms-access foreign-keys

我有两张桌子:玩家和GameLog如下

玩家有(Player_ID,FirstName,LastName,Position)

GameLog有(FirstName,LastName,Pts,Date_Played)

我担心设计有点差,但我想现在链接这两个表,所以我想将Player_ID添加到GameLog并使其成为Players表的外键。

如果我在两个表中都有数据,有没有办法做到这一点?

所以,如果玩家有:

Player_ID, FirstName, LastName, Position
1, Kevin, Love, PF

GameLog有:

FirstName, LastName, Pts, Date_Played
Kevin, Love, 24, 2/25/2014

我希望GameLog成为:

Player_ID, FirstName, LastName, Pts, Date_Played
1, Kevin, Love, 24, 2/25/2014

2 个答案:

答案 0 :(得分:0)

有两种方法可以实现这一点。

首先,您可以添加hte字段,允许空值,然后将其设置为向前填充它。

然后从那里写一个匹配(可能在名称上),允许你填充你可以肯定的hte行。

您可以立即申请FK,因为null不必有相应的记录。

答案 1 :(得分:0)

您显示的结果会建议查询,例如:

SELECT players.Player_ID, players.FirstName, 
       players.LastName, gamelog.Pts, gamelog.Date_Played
FROM gamelog INNER JOIN players ON (gamelog.LastName = players.LastName) 
       AND (gamelog.FirstName = players.FirstName)

但是,创建一个新表会好得多:

SELECT players.Player_ID, gamelog.Pts, gamelog.Date_Played 
     INTO gamelog2
FROM gamelog INNER JOIN players ON (gamelog.LastName = players.LastName) 
     AND (gamelog.FirstName = players.FirstName);

这将允许您检查新表,然后将其替换为游戏日志。当游戏日志具有外键ID时,没有理由将玩家表中的名称保存起来。您可能希望将ID重命名为PlayerID并向游戏日志添加自动编号。