multiple tables need one to many relationship

后端 未结 5 1476
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 19:39

I have a SQL database with multiple tables: A, B, C, D. Entities in those tables are quite different things, with different columns, and different kind of relations between

5条回答
  •  孤城傲影
    2020-12-05 20:01

    I presume that you are talking of a single comments table with a foreign key to "exactly one of" A, B, C or D.

    The fact that SQL cannot handle this is one of its fundamental weaknesses. The question gets asked over and over and over again.

    See, e.g.

    What is the best way to enforce a 'subset' relationship with integrity constraints

    Your constraint is a "foreign key" from your "single comments" table into a view, which is the union of the identifiers in A, B, C and D. SQL supports only foreign keys into base tables.

    Observe that SQL as a language does have support for your situation, in the form of CREATE ASSERTION. I know of no SQL products that support that statement, however.

    EDIT You should also keep in mind that with a 'single' comments table, you might need to enforce disjointness between the keys in A,B,C and D, for otherwise it might happen some time that a comment automatically gets "shared" between entity occurrences from different tables, which might not be desirable.

提交回复
热议问题