制作受“引用”约束的 varchar 数组;在 SQL 中
想象
CREATE TABLE titles (
bookTitle varchar(80)
);
CREATE TABLE borrowers (
name varchar(80), --borrower's name
checkedOut varchar(80)[] references titles(bookTitle) --list of checked out
);
一下,当然这不起作用,但它(希望)能够让人类读者明白我想要的东西:我希望借阅者在一列中有一个数组(因为一次可以签出多个标题)并且我想要确保只有标题表中的标题才可能出现在借阅者的已检出标题列表中。这个的语法是什么?
Imagine
CREATE TABLE titles (
bookTitle varchar(80)
);
CREATE TABLE borrowers (
name varchar(80), --borrower's name
checkedOut varchar(80)[] references titles(bookTitle) --list of checked out
);
Of course that's not working, but it (hopefully) gets across to you the human reader what I want: I want borrowers to have in one column an array (since more than one title could be checked out at a time) and I want to be sure that only titles that are in the titles table are possible in the borrower's list of checked out titles. What is the syntax for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不引入第三个表并将该借款人姓名的所有签出信息存储在其中?在我看来,将数组强制放入数据库字段就像苹果和橘子一样。
Why not introduce a third table and store all the checkedOut for that borrower name in there? Forcing an array into a database field is apples and oranges in my opinion.
通过存储数组,您可以说违反了原子性原则,因此违反了第一个法线形式。为什么不创建一个“正确的”关系数据模型呢?
如果一本书一次只能被一个人借阅,那么您的数据模型中需要一个 N:1 关系,这可以通过一个简单的 FOREIGN KEY 来实现:
(如果标题当前未被任何人借用,
TITLE.BORROWED_BY
可以设置为 NULL。)如果一本书可以同时被多人借阅(无论这意味着什么),您的模型将需要 M:N 关系,可以通过中间的附加“链接”表来建模:
By storing an array, you are arguably violating the principle of atomicity and thus the first normal form. Why not make a "proper" relational data model instead?
If a single book can be borrowed by no more than one person at a time, you need an N:1 relationship in your data model, which can be achieved by a simple FOREIGN KEY:
(The
TITLE.BORROWED_BY
can be set to NULL if the title is currently not borrowed by anyone.)If a single book can be borrowed by multiple persons at a time (whatever that might mean), your model would need an M:N relationship, which can be modeled by an additional "link" table in the middle:
你不能(直接)。关系数据库没有数组;它们有表(关系)以及它们之间的关系。因此,SQL 没有数组的概念。
你可以这样做:
但这是非正常,违反了第一范式:它有重复的组。
你想要的模式是这样的
You can't (directly). Relational databases don't have arrays; they have tables (relations) and relationship between them. Consequently, SQL doesn't have the notion of an array.
You could do something like:
but that is non-normal, violating 1st Normal Form: it has repeating groups.
The schema you want is something like