2012-02-22 60 views
0

想象使通過SQL中的「引用」約束VARCHAR處理數組

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 
); 

當然這不是工作,而是跨越它(希望)得到你的人的讀者什麼,我想:我要借款人在一列中有一個數組(因爲一次可以檢出多個標題),我想確保在借閱者的檢出標題列表中只有標題表中的標題是可能的。這是什麼語法?

回答

3

爲什麼不引入第三個表並將所有checkedOut存儲在該借用者名稱中?在我看來,將數組強制爲數據庫字段是蘋果和桔子。

CREATE TABLE titles (
    bookTitle varchar(80) 
); 

CREATE TABLE borrowers (
    name varchar(80) --borrower's name 
); 

CREATE TABLE checkedout (
    name  varchar(80), 
    bookTitle varchar(80) 
); 
+0

好吧,那麼我不得不checkedout.name具有參考借款人(名稱)和checkedout.bookTitle引用標題(BOOKTITLE) – mring 2012-02-22 19:46:10

+1

我與BD同意。不過,我認爲你應該添加自動遞增主鍵,交叉表應該引用這些鍵,而不是名稱。我認爲這將解決您的擔憂。 – northpole 2012-02-22 19:49:09

+1

@northpole你正在談論自然與替代鍵。這兩種方法都有其優點,但沒有一個是絕對「更好」的 - 這取決於具體情況。 – 2012-02-22 20:01:53

2

通過存儲數組,您可能違反了atomicity的原則,因此也是第一種標準形式。爲什麼不建立一個「適當的」關係數據模型呢?

如果一本圖書可以通過在時間不超過一人借來的,你需要一個N:在您的數據模型1間的關係,這可以通過一個簡單的外鍵來實現:

enter image description here

(該TITLE.BORROWED_BY可如果標題是目前不被任何人借設置爲NULL。)

如果一本書可以被多個人員在同一時間(無論這可能意味着)借用,您的模型將需要M:N關係,可以是mod通過一個額外的 「鏈接」 表在中間ELED:

enter image description here

0

你不能(直接)。關係數據庫沒有數組;他們有表格(關係)和他們之間的關係。因此,SQL不具有數組的概念。

你可以這樣做:

create table foo 
(
    id int not null primary key , 
    col_01 varchar(200) null , 
    col_02 varchar(200) null , 
    ... 
    col_nn varchar(200) null , 
) 

但那是non-normal,違反1st Normal Form:它已經重複的組。

你想要的模式是一樣的東西

create table book 
(
    id   int   not null primary key , -- primary key 
    isbn  varchar(32)  null , 
    title varchar(80) not null , -- can't use title as a key as titles are not unique 
) 

-- you might have multiple copies of the same book 
create table book_copy 
(
    book_id  int not null , 
    copy_number int not null , 

    primary key (book_id , copy_number) , 

    foreign key (book_id) references book(id) , 

) 

create table customer 
(
    id  int   not null primary key , 
    surname varchar(32) not null , 
    name varchar(32) not null , 
) 

create table customer_has_book 
(
    customer_id int not null , 
    book_id  int not null , 
    copy_number int not null , 

    primary key (customer_id , book_id , copy_number) , -- customer+book+copy number is unique 

    unique (book_id , copy_number) , -- a given copy may only be borrowed one at a time  

    foreign key (customer_id) references customer(id) , 
    foreign key (book_id , copy_number) references book_copy(book_id,copy_number) , 

)