2016-07-15 73 views
-1

我在2個不同的數據庫中創建了2個表。第一個數據庫名稱是包含userDetails表的用戶,它具有id作爲主鍵和user_name,而我的第二個數據庫是具有1個稱爲customerDetails的表的客戶,其具有1個作爲主鍵和客戶名稱的一個表以及一個以上的視圖用戶表中包含該用戶表和名稱的ID。視圖與表之間的主鍵和外鍵鍵映射

所以我想要做的是,在customerDetails表中創建該視圖的外鍵,以便我可以通過視圖訪問來自客戶數據庫的用戶表。我不知道如何實現這一點,因爲我是數據庫概念的新手,請任何人都可以幫我解決這個問題。

整個場景是如下,

> Database Name : user 
> Table Name : userDetails 
> Fields  : id userName 
> 
> Database Name : customer 
> View Name  : user_view 
> Fields  : id userName 
> 
> Database Name : customer 
> View Name  : customerDetails 
> Fields  : id  custName 

我想在最後一個表是在爲CustomerDetails最後一列從視圖的外鍵。我怎樣才能做到這一點?

+0

'FOREIGN KEYS'用於限制您可以插入表格列的內容。我想你正在尋找的是一個'JOIN',它用於從兩個表中獲取數據,並將它們連接在一起。 – Fredster

+0

「視圖」預先準備好了不影響「FOREIGN KEYS」的SELECT語句。 – Fredster

+0

是的,我想從userDetails表中的數據,但它存在於另一個數據庫稱爲用戶,所以要訪問它在客戶數據庫我創建該userDetails表的視圖在這裏,我如何使用id的userDetails表作爲外鍵在我的customerDetails表中? –

回答

1

查看數量是不是與外鍵相關的數據,就像您在同行評論中提到的一樣。下面使用連接表來交叉用戶和公司,在數據庫之間實施外鍵約束(對於數據庫之間的共享信息不是一個壞主意)。

連接表是多對多的,並將用戶和公司連接在一起。

模式:

create schema userDB; 
create table userDB.userDetails 
( id int auto_increment primary key, 
    userName varchar(100) not null 
); 

create schema customerDB; 
create table customerDB.customerDetails 
( id int auto_increment primary key, 
    custName varchar(100) not null 
); 

create table customerDB.userCustomerJunction 
( -- a many-to-many mapping 
    id int auto_increment primary key, 
    userId int not null, 
    custId int not null, 
    unique key (userId,custId), -- no dupes allowed 
    foreign key `ucj_2_user` (userId) references userDB.userDetails(id), 
    foreign key `ucj_2_cust` (custId) references customerDb.customerDetails(id) 
); 

測試:

insert customerDB.customerDetails(custName) values ('Exxon Mobil'); -- id 1 
insert customerDB.userCustomerJunction(userId,custId) values (1,7); -- FK Failure 
-- above line generates an error 1452 as expected 
insert userDB.userDetails(userName) values ('Kelly'); -- id 1 
insert customerDB.userCustomerJunction(userId,custId) values (1,1); -- success, FK's satisfied 

記住用戶和公司是獨立的實體和接口兩種需要的東西捆綁在一起。聯結表是一個很棒的地方,可以放置一列,如effectiveRights或其他東西。它會表示用戶可以做什麼,如插入,更新,刪除,查看,黑名單等。

在用戶和公司之間創建視圖就像任何聯接一樣,但在這種情況下,它將在數據庫之間表名前面的whichDB.。這個觀點被物化並在物理表格中表現出來。因此,作爲物理規則,物理實體具有FK的有效性(數據完整性)。並且,effectiveRights列的添加將幫助您確定每個用戶和公司可以一起完成的操作:例如,該用戶對該公司信息具有某些權限等。通過權限位標記或單獨的權限列,所有在Junction表中。有關連接表的示例,請參閱我的Answer