简体   繁体   中英

one to one relationship between three tables

在此输入图像描述

Hi I want to achieve one ot one relation ship between three tables such that rtTicketId (1) can only be used vmID(1) and cannot be used by dbId(1).

create table IF NOT EXISTS RequestTable (
  rtTicketId bigserial unique not null AUTO_INCREMENT, 
  primary key (rtTicketId));

create table IF NOT EXISTS Vm (
  vmId bigserial unique not null AUTO_INCREMENT, 
  primary key (vmId),
  foreign key (rtTicketId) references RequestTable(rtTicketId));

create table IF NOT EXISTS Db (
  dbId bigserial unique not null AUTO_INCREMENT, 
  rtTicketId bigserial unique not null,
  primary key (dbId),
  foreign key (rtTicketId) references RequestTable(rtTicketId));

I have Done this but this create one to one relation between only two separately. I want rt id to be unique . right now both vm and db table are able to use same rtTicketId to connect to request table. I dont want that

Maybe polymorphic association will help; eg Instead of VM as DB has a column to store rtTicketId, RT will have 2 columns, fkId and fkType for example, fkId stores the primary key in VM or DB and fkType defines where to look at when querying (DB or VM).

See also here: Possible to do a MySQL foreign key to one of two possible tables?

Another option I can think about is doing this programmatically such as:

SELECT * FROM RequestTable WHERE rtTicketId NOT IN (SELECT DISTINCT rtTicketId FROM your_other_table_vm_or_db)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM