0

I have Table A, Table B, and Table C. Table C has a column which should be a FK for a PK. The PK could be either Table A's id or Table B's id. What is the best practice to design such tables?

I am thinking of creating 2 columns in Table C, where the first one would determine either Table A or Table B, and the second one represents the id of either Table A or Table B (depending on the first column). Is it the right way to do it?

4

2 回答 2

1

I am thinking of creating 2 columns in Table C, where the first one would determine either Table A or Table B, and the second one represents the id of either Table A or Table B (depending on the first column). Is it the right way to do it?

No. You would be preventing the DBMS from enforcing the foreign key. You'd have to enforce the FK through triggers or the application code, which is more prone to errors and potentially less performant.

Either make two FK fields (one for Table A, other for Table B) and use a CHECK1 to ensure only one of them is not NULL, or use inheritance.

More info in this post.


1 Unfortunately, MySQL parses but doesn't enforce CHECK constraints, so you'll need to use a trigger instead. This limitation doesn't exist in other DBMSes.

于 2013-05-01T02:38:39.123 回答
1

使用 SQL UNION 组合两个具有不同连接的 ResultSet

见:http ://www.sqlfiddle.com/#!8/3519e/4

我用 3 个表做了一个例子:

  • 卡车
  • DRIVER_ASSIGNED

您可以创建一个查询以将 A 与 C 连接,另一个以将 B 与 C 连接,并使用 UNION 连接两个结果集。例如:

(select * from `A`, 
`C`
where `A`.ID = `C`.`ID` and
`C`.`Type` like 'A')
UNION
(select * from `B`, 
`C`
where `B`.ID = `C`.`ID` and
`C`.`Type` like 'B')

关于类和子类

似乎 TABLE A 和 TABLE B 是另一种类型/类的子类型。因此,例如,表 A 可能是汽车,表 B 可能是卡车,但它们扩展了车辆。

在这种情况下,我认为您需要第四个表 TABLE PARENT,它将结合 A 和 B 的公共字段。C 将使用 TABLE PARENT 的主键作为外部 K。

表 A 和 B 将同时包含作为外键,但也可能作为表 PARENT 的主键作为主键。

因此,使用我与车辆的类比让我们假设:

    TABLE A = CARS
    TABLE B = TRUCKS
    TABLE C = ASSIGNED_DRIVERS
    TABLE PARENT = VEHICLES

    TABLE VEHICLES - PARENT of A and B
    -------------
    ID (PK)
    HORSE POWER
    LICENSE PLATE
    etc...

    TABLE CARS - 
    -------------
    ID (PK)
    VEHICLE_ID (FK linking to VEHICLES.ID)
    NUMBER_SEATS
etc...

    TABLE TRUCKS - 
    -------------
    ID (PK)
    VEHICLE_ID (FK linking to VEHICLES.ID)
    HIGHT (meters)
    MAXIMUM_STORAGE_WEIGHT
etc...


    TABLE DRIVERS_ID - 
    -------------
    VEHICLE_ID (FK linking to VEHICLES.ID)
    DRIVER_OD
  START_DATE
END_DATE
etc...

因此,以下方法将使您摆脱这个问题,并且在语义上也更正确。

您还可以查看在线文档,例如:

http://www.dssbooks.com/web/Files/LookInside/Web-DSS-Chapter-03.pdf(第 55 页)查看类和子类之间的理论。

于 2013-04-30T19:53:17.907 回答