multiple tables need one to many relationship

后端 未结 5 1474
伪装坚强ぢ
伪装坚强ぢ 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:04

    Create a comment table with a comment_id primary key and the various attributes of a comment.

    Additionally, create A_comment thus:

    CREATE TABLE A_comment (
        comment_id PRIMARY KEY REFERENCES comment(comment_id),
        A_id REFERENCES A(A_id)
    )
    

    Do likewise for B, C and D. This ensures referential integrity between comment and all the other tables, which you can't do if you store the ids to A, B, C and D directly in comment.

    Declaring A_comment.comment_id as the primary key ensures that a comment can only belong to one entry in A. It doesn't prevent a comment from belonging to an entry in A and an entry in B, but there's only so much you can achieve with foreign keys; this would require database-level constraints, which no database I know of supports.

    This design also doesn't prevent orphaned comments, but I can't think of any way to prevent this in SQL, except, of course, to do the very thing you wanted to avoid: create multiple comment tables.

提交回复
热议问题