简体   繁体   中英

How to create member_follower table structure?

I have one member table structure in SQL Server:

member_table

memberid name address email
111      aaa  IND     a@a.com
222      bbb  UK      b@b.com

Now I want to give such facility that one member can follow as many other members. How can I do that?

Should I create a new table? Should I use any flags?

I'm thiking to create a new table and give Member table

You can create another table consisting of two attributes (member_id, follows_member_id) This table keeps records of each member following other members. Both attributes reference your members table. This is a standard approach in creating a many-many relation as it is normalized. read more

I would create a junction table with a key on both member_ids to ensure there is at most 1 row.

I try to not cater to YGWITs (your gonna want it), but it seems a subscription table would call for some additional metadata such as the date the subscription starts or the last access date to know if there is new activity.

I would end up with something like this:

CREATE TABLE [dbo].[member_subscription](
    [member_id] [int] NOT NULL,
    [target_member_id] [int] NOT NULL,
    [date_created] [datetime] NOT NULL,
    [date_last_visit] [datetime] NULL,
    CONSTRAINT [PK_member_subscription] PRIMARY KEY CLUSTERED 
    (   -- key on both member_id fields
        [member_id] ASC,
        [target_member_id] ASC
    ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

-- Foreign key contrain for member_id
ALTER TABLE [dbo].[member_subscription]  WITH CHECK ADD  CONSTRAINT [FK_member_subscription_member] FOREIGN KEY([member_id])
REFERENCES [dbo].[member] ([member_id])
GO
ALTER TABLE [dbo].[member_subscription] CHECK CONSTRAINT [FK_member_subscription_member]
GO


-- Foreign key contrain for target_member_id
ALTER TABLE [dbo].[member_subscription]  WITH CHECK ADD  CONSTRAINT [FK_member_subscription_target_member] FOREIGN KEY([target_member_id])
REFERENCES [dbo].[member] ([member_id])
GO
ALTER TABLE [dbo].[member_subscription] CHECK CONSTRAINT [FK_member_subscription_target_member]
GO

-- Default value for date_created
ALTER TABLE [dbo].[member_subscription] ADD  CONSTRAINT [DF_member_subscription_datecreated]  DEFAULT (getdate()) FOR [date_created]
GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM