在SQL中强制执行一对零或一关系

在SQL中强制执行一对零或一关系,sql,Sql,我在stackoverflow上找到了一个如何实施1对1关系()的示例,但我想知道如何在1对0或1关系中使用这个示例 create table Users ( UserId int not null primary key, . . . . . . PrimaryEmailId int not null, constraint fk_PrimaryEmailId foreign key (UserId, PrimaryEmailId) references Use

我在stackoverflow上找到了一个如何实施1对1关系()的示例,但我想知道如何在1对0或1关系中使用这个示例

create table Users (
    UserId int not null primary key, . . .
    . . .
    PrimaryEmailId int not null,
    constraint fk_PrimaryEmailId foreign key (UserId, PrimaryEmailId) references UserEmails(UserId, UserEmailId)
);

create table UserEmails (
    UserEmailId int not null primary key,
    UserId int not null,
    . . .,
    unique (UserId, UserEmailId),
    constraint fk_UserEmails_UserId foreign key (UserId) references Users(UserId)
);

我不完全确定怎么做。我的猜测是,我只想从UserEmails表的UserId字段中删除notnull约束,但我不确定。请有人解释一下如何正确执行此操作,非常感谢。

您只需删除
notnull
约束:

create table Emails (
    EmailId int not null primary key,
    . . .,
);

create table Users (
    UserId int not null primary key, . . .
    . . .
    PrimaryEmailId int,
    constraint fk_PrimaryEmailId foreign key (PrimaryEmailId) references UserEmails(UserEmailId),
    contraint unq_users_primaryemailid unique(primaryemailid)
);
您也不希望在
UserEmails
中使用
UserId
。我看不出它有什么用


因此,
PrimaryEmailId
具有外键约束;它可以是
NULL
,因此为0/1。
unique
约束保证两个用户不能拥有相同的主电子邮件。

如果你说的是给定的
用户ID没有电子邮件地址,那只是一个不在
用户电子邮件中插入记录的问题。如果这不是你的意思,请你的问题,以更好地解释你试图实现什么。@RandomStacker。请详细解释您想要的确切关系。您想要在您的用户电子邮件中记录不属于用户的内容吗?您想为一个用户发送多封电子邮件吗?