SQL - 外键约束和基数

标签 sql sqlite cardinality

有人可以解释一下外键约束和基数吗?我正在阅读 SQLite 手册,并且位于 advanced foreign key constraint features 部分。在其解释中写道:

Parent and child keys must have the same cardinality. In SQLite, if any of the child key columns (in this case songartist and songalbum) are NULL, then there is no requirement for a corresponding row in the parent table.

我知道基数应该是一组值的数量,或者至少在数学中是这样,所以我假设如果我有十个人记录,每个记录都有性别列,那么有两种可能性:男性和女性,所以假设有一些男性和一些女性,基数是 2...对吗?

我在谷歌上搜索了一下,没有找到太多。我发现的最接近的东西是 Visio 2003 的 Microsoft 页面,其中有一个部分解释“About attributes, referential integrity, and cardinality”。它说:

The cardinality of a relationship describes how many records in a parent table can be directly related to records in a child table. Cardinality is expressed in terms such as one-to-one, one-to-many, many-to-one, or many-to-many.

这可能是一个很好的描述,但我仍然不明白 SQLite 当它说父键和子键必须具有相同的基数时意味着什么。如果您可以在答案中举一些例子,那也会有帮助。谢谢

最佳答案

这是示例的表结构:

CREATE TABLE album(
  albumartist TEXT,
  albumname TEXT,
  albumcover BINARY,
  PRIMARY KEY(albumartist, albumname)
);

CREATE TABLE song(
  songid     INTEGER,
  songartist TEXT,
  songalbum TEXT,
  songname   TEXT,
  FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname)
);

父表(album)有一个复合主键,即主键由两列组成。

因此,如果子表想要引用专辑,它也必须使用两列。

在本例中,父键和子键的基数均为 2。

关于SQL - 外键约束和基数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071125/

相关文章:

sql - 更改 ORDER BY 会导致 "error converting data type"

mysql索引 'and'总是选择第一个创建的索引?

mysql - 按时间排序和分组

sql - 用一个范围内的随机数更新每条记录

wpf - 如何在wpf中创建sqlite数据库?

Android 全局 SQLite 数据库访问

performance - 术语聚合性能高基数

mysql - SQL中基数的定义是什么

sql - 为了创建我的模型,我需要执行一个非常困难的查询

database - 在 VB6 中使用 SQLITE