adding CHECK to impose constraints on more than one table

后端 未结 4 1674
我在风中等你
我在风中等你 2021-01-29 02:57

I want to modify the following DDL to add CHECK constraints so that the manager of a store works at the same store and a store supplies all the products if its type is \'local\'

4条回答
  •  深忆病人
    2021-01-29 03:45

    You can do this by changing your primary key in works_at, then adding unique constraints to ensure the uniqueness. This will be better than using check constraints:

    CREATE TABLE works_at(
      employee_number CHAR(5),
      store_code CHAR(5),
      PRIMARY KEY(employee_number, store_code),
      FOREIGN KEY(employee_number) REFERENCES employee,
      FOREIGN KEY(store_code) REFERENCES store,
      CONSTRAINT UQ_Works_at_employee_number UNIQUE NONCLUSTERED(employee_number) -- ENSURES EMPLOYEE CAN ONLY WORK AT ONE STORE
      )
    

    Then your manages table can reference works_at to ensure they manage the store they work at:

    CREATE TABLE manages(
      employee_number CHAR(5),
      store_code CHAR(5),
      PRIMARY KEY(store_code),
      FOREIGN KEY(employee_number, store_code) REFERENCES works_at (employee_number, store_code)
      )
    

    With regard to your second part, I don't see a way of enforcing the fact that stocks must contain all stores and all products, and this also seems kind of pointless, you are essentially asking for a table that is just a cross join of two other tables.

提交回复
热议问题