3表之间的SQL关系

时间:2014-10-05 17:46:37

标签: sql sql-server

我正在做一个由三个表组成的课程项目:会员,活动和出席。

  • 会员表包含:MID作为主键,名称,地址等......并且与出勤有一个或多个到0或多个关系
  • 事件表包含:EventNo作为主键,EventName等...并且与出勤有一个或多个到0或多个关系
  • 出席时间包含:MID和EventNo

我可以创建表格,但我不理解他们的关系。谁能简单解释一下他们之间的关系并帮我写代码???提前致谢

2 个答案:

答案 0 :(得分:0)

例如:

create table member (
  MID INT primary key ...,
  Name VARCHAR(30),
  ...
);

create table event (
  EventNo INT primary key ...,
  EventName VARCHAR(30),
  ...
);

create table attenance (
  EventNo INT,
  MID INT,
  //here add constraint for MID and EventNo - they are  foreign key from other tables.
  UNIQUE(EventNo, MID)
);

看来,事件和成员之间有关系:many-to-manyOne member可以在many eventsOne event可以many members

拼写纠正

答案 1 :(得分:0)

CREATE TABLE Member
    ([MID] int primary key, [Name] varchar(5), [Address] varchar(8))
;

INSERT INTO Member
    ([MID], [Name], [Address])
VALUES
    (1, 'Name1', 'Address1')
;



CREATE TABLE Event
    ([EventNo] int primary key, [EventName] varchar(6))
;

INSERT INTO Event
    ([EventNo], [EventName])
VALUES
    (1, 'Event1')
;

    CREATE TABLE Attendance
        ([EventNo] int FOREIGN KEY REFERENCES Event(EventNo), [MID] int FOREIGN KEY REFERENCES Member(MID))
    ;

INSERT INTO Attendance
    ([EventNo], [MID])
VALUES
    (1, 1)
;

选择查询将是这样的

select * from Event join Attendance on Event.EventNo=Attendance.EventNo
join Member on Member.MID=Attendance.MID

DEMO