且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在多个表中引用主键的外键?

更新时间:2023-01-29 09:31:35

假设我已经正确地理解了你的场景,这就是我所说的 right 方法:

您的数据库的级别描述!你有雇员,雇员可以是雇员雇员和雇员雇员(不管这些是什么)。在面向对象方面,有一个类雇员,有两个子类叫做ce employee和sn employee。

然后你把这个更高的 - 三级表描述: employees employees_ce employees_sn


  • employees(id,name)

  • employees_ce(id,ce-specific stuff)

  • employees_sn(id,sn-specific因为所有的员工都是员工(duh!),所以每个员工都会有一个行 employees 表。 ce员工在 employees_ce 表中有一行,而sn员工也在 employee_sn 中有一行>表。 employees_ce.id employees.id 的外键,就像 employees_sn.id 是。

    要引用任何类型的员工(ce或sn),请参阅 employees 表。也就是说,你遇到的外键应该引用该表!


    I have to two tables namely employees_ce and employees_sn under the database employees.

    They both have their respective unique primary key columns.

    I have another table called deductions, whose foreign key column I want to reference to primary keys of employees_ce as well as employees_sn. Is this possible?

    for example

    employees_ce
    --------------
    empid   name
    khce1   prince
    
    employees_sn
    ----------------
    empid   name
    khsn1   princess
    

    so is this possible?

    deductions
    --------------
    id      name
    khce1   gold
    khsn1   silver
    

    Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:

    Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".

    Then you translate this higher-level description to three tables: employees, employees_ce and employees_sn:

    • employees(id, name)
    • employees_ce(id, ce-specific stuff)
    • employees_sn(id, sn-specific stuff)

    Since all employees are employees (duh!), every employee will have a row in the employees table. "ce" employees also have a row in the employees_ce table, and "sn" employees also have a row in the employees_sn table. employees_ce.id is a foreign key to employees.id, just as employees_sn.id is.

    To refer to an employee of any kind (ce or sn), refer to the employees table. That is, the foreign key you had trouble with should refer to that table!