查看數量是不是與外鍵相關的數據,就像您在同行評論中提到的一樣。下面使用連接表來交叉用戶和公司,在數據庫之間實施外鍵約束(對於數據庫之間的共享信息不是一個壞主意)。
連接表是多對多的,並將用戶和公司連接在一起。
模式:
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。
'FOREIGN KEYS'用於限制您可以插入表格列的內容。我想你正在尋找的是一個'JOIN',它用於從兩個表中獲取數據,並將它們連接在一起。 – Fredster
「視圖」預先準備好了不影響「FOREIGN KEYS」的SELECT語句。 – Fredster
是的,我想從userDetails表中的數據,但它存在於另一個數據庫稱爲用戶,所以要訪問它在客戶數據庫我創建該userDetails表的視圖在這裏,我如何使用id的userDetails表作爲外鍵在我的customerDetails表中? –