我有两张桌子:会谈和日子。会谈看起来像:
+----+----------------------------------+--------+
| Id | Name | Leader |
+----+----------------------------------+--------+
| 1 | How to improve revenue for tacos | Tacob |
| 2 | Improving sales potential | Bocat |
+----+----------------------------------+--------+
和日子:
+--------+-----+
| TalkId | Day |
+--------+-----+
| 1 | Mon |
| 1 | Tue |
| 1 | Thu |
| 2 | Mon |
| 2 | Tue |
+--------+-----+
TalkId
是引用Talks
表的外键。
外键强制执行" A Day需要Talk"的关系。但是,我还想强制执行相反的关系"谈话需要至少一天"。
我知道这个约束类似于多对多关系,两个记录都相互依赖。但是,在这种情况下,很多天引用一个讲话,但只有一个讲话引用很多天。
另一个问题是,在创建这样的约束之后,如何一次插入两个记录?
我已经搜索了其他问题,但只找到了多对多关系的案例,结果如下:
+----+----------------------------------+--------+
| Id | Name | Leader |
+----+----------------------------------+--------+
| 1 | How to improve revenue for tacos | Tacob |
| 2 | Improving sales potential | Bocat |
+----+----------------------------------+--------+
+----+-----+
| Id | Day |
+----+-----+
| 1 | Mon |
| 2 | Tue |
| 3 | Thu |
| 4 | Mon |
| 5 | Tue |
+----+-----+
+--------+-------+
| TalkId | DayId |
+--------+-------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 2 | 5 |
+--------+-------+
其中TalkId
引用Talks
Id
和DayId
引用Days
' s Id
。
修改:
忽略我上面要求的内容。
我希望能够做到:
SELECT
全部有效Talks
SELECT
全部有效Days
我希望无法做到:
INSERT
Talk
没有Day
INSERT
Day
没有Talk
答案 0 :(得分:0)
听起来你想要一个简单的外键关系:
alter table days add constraint fk_days_talkid foreign key (talkid) references talks(talkid);
这可以保证talkid
有效。然后,您将days.talkid
声明为not null
,并保证您描述的关系。
答案 1 :(得分:0)
-- Day named (TheDay) exists. -- Calendar {TheDay} PK {TheDay} -- Talk (TalkID) titled (TalkName), presented by (Leader) is by default -- scheduled on (DefaultDay). Talk {TalkID, TalkName, Leader, DefaultDay} PK {TalkID} AK {TalkName} FOREIGN KEY {DefaultDay} REFERENCES Calendar {TheDay} --Talk (TalkID) is also scheduled on (TheDay). -- TalkDay {TalkID, TheDay} PK {TalkID, TheDay} FOREIGN KEY {TalkID} REFERENCES Talk {TalkID} FOREIGN KEY {TheDay} REFERENCES Calendar {TheDay}
Note PK = primary key AK = alternate key (unique) All attributes (columns) NOT NULL
选择特定演讲的所有日期:
select TalkName, DefaultDay as TalkDay from Talk where TalkName = 'How to improve revenue for tacos' union select TalkName, b.TheDay as TalkDay from Talk as a join TalkDay as b on b.TalkID = a.TalkID where a.TalkName = 'How to improve revenue for tacos'
选择特定日期的所有讲座:
select TalkName, DefaultDay as TalkDay from Talk where DefaultDay = 'Tue' union select TalkName, b.TheDay as TalkDay from Talk as a join TalkDay as b on b.TalkID = a.TalkID where b.TheDay = 'Tue'