sql 需要 n:m 关系
sql required n:m relation
如何实现这个概念:
"An Article has at least one Author"
引用似乎在本质上变成了循环,即 ArticleAuthors 引用 Article,但是 Article 也必须引用 ArticleAuthors...
create domain Email varchar;
create table Authors(
authorEmail Email primary key,
authorName varchar not null
);
create table ArticleAuthors(
article int references Article,
author varchar references Authors,
primary key (article, author)
)
create table Article(
articleID int primary key,
articleAuthors ??? not null
)
即我用什么代替 ???
在 SQL RDBMS 中,通常您不能同时插入两个 table。所以你不能有严格的执行。
您通常会定义一些存储过程来处理整个事务。
所以 Article
不需要引用 Authors
。
FUNCTION (articleID, authors[])
if authors is null then exit function;
START TRANSACTION
INSERT INTO Article
INSERT INTO ArticleAuthors
END TRANSACTION
并且您还需要 DELETE on Authors
的触发器,以确保您不会删除一篇文章中的所有作者。
SQL DBMS 通常无法单独使用 DDL 在 table 之间实现这种 "at least one" 约束。原则上,答案可能是使用 CREATE ASSERTION 并推迟约束检查,直到更新两个 table 之后。然而,大多数 SQL DBMS(我所知道的所有这些)都不允许这样做。它实际上是 SQL 的限制,因为 SQL 不支持多 table 更新。
如何实现这个概念:
"An Article has at least one Author"
引用似乎在本质上变成了循环,即 ArticleAuthors 引用 Article,但是 Article 也必须引用 ArticleAuthors...
create domain Email varchar;
create table Authors(
authorEmail Email primary key,
authorName varchar not null
);
create table ArticleAuthors(
article int references Article,
author varchar references Authors,
primary key (article, author)
)
create table Article(
articleID int primary key,
articleAuthors ??? not null
)
即我用什么代替 ???
在 SQL RDBMS 中,通常您不能同时插入两个 table。所以你不能有严格的执行。
您通常会定义一些存储过程来处理整个事务。
所以 Article
不需要引用 Authors
。
FUNCTION (articleID, authors[])
if authors is null then exit function;
START TRANSACTION
INSERT INTO Article
INSERT INTO ArticleAuthors
END TRANSACTION
并且您还需要 DELETE on Authors
的触发器,以确保您不会删除一篇文章中的所有作者。
SQL DBMS 通常无法单独使用 DDL 在 table 之间实现这种 "at least one" 约束。原则上,答案可能是使用 CREATE ASSERTION 并推迟约束检查,直到更新两个 table 之后。然而,大多数 SQL DBMS(我所知道的所有这些)都不允许这样做。它实际上是 SQL 的限制,因为 SQL 不支持多 table 更新。