How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

前端 未结 4 606
野趣味
野趣味 2020-11-22 04:51

Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?

4条回答
  •  醉梦人生
    2020-11-22 05:23

    One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

    One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

    Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

    -- This table will hold our phone calls.
    CREATE TABLE dbo.PhoneCalls
    (
       ID INT IDENTITY(1, 1) NOT NULL,
       CallTime DATETIME NOT NULL DEFAULT GETDATE(),
       CallerPhoneNumber CHAR(10) NOT NULL
    )
    -- This table will hold our "tickets" (or cases).
    CREATE TABLE dbo.Tickets
    (
       ID INT IDENTITY(1, 1) NOT NULL,
       CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
       Subject VARCHAR(250) NOT NULL,
       Notes VARCHAR(8000) NOT NULL,
       Completed BIT NOT NULL DEFAULT 0
    )
    -- This table will link a phone call with a ticket.
    CREATE TABLE dbo.PhoneCalls_Tickets
    (
       PhoneCallID INT NOT NULL,
       TicketID INT NOT NULL
    )
    

提交回复
热议问题