简体   繁体   English

mysql外键使用主键

[英]mysql foreign key using primary key

I have two tables, diary with columns id primary key Narrative text and master with columns id primary key Diaryid int EventDate date Location int我有两个表,带有列 id 主键的日记和带有列 id 主键的主键 Diaryid int EventDate date Location int

I want to ensure that master(Diaryid) is always a valid diary(id)我想确保 master(Diaryid) 始终是有效的 diary(id)

Can I use foreign key to achieve this?我可以使用外键来实现这一点吗? Bearing in mind that one key is a primary key and the other int.请记住,一个键是主键,另一个是 int。

Any advice would be apprecaited.任何建议将不胜感激。

Yes you cqan achieve this by using a FOREIGN KEY .是的,您可以通过使用FOREIGN KEY来实现这一点。

Also you should define it as NOT NULL, so that only exiasting diary keys are allowed您还应该将其定义为 NOT NULL,以便只允许使用现有的日记键

CREATE TABLE master(Diaryid BIGINT NOT NULL
,  FOREIGN KEY (Diaryid)
        REFERENCES diary(id)
        );

You cqan add你cqan添加

ON DELETE CASCADE

So that the Master row will be deleted also when the diary rows gets removed这样当日记行被删除时,主行也将被删除

Don't know what is different but problem is solved.不知道有什么不同,但问题解决了。 CREATE TABLE diary (id int AUTO_INCREMENT, Narrative text, PRIMARY KEY( id )) CREATE TABLE master ( id int AUTO_INCREMENT, Diaryid int, datemade date, FOREIGN KEY( Diaryid ) REFERENCES diary ( id ), primary key (id)) So am now adding diary records and can have multiple master records so long as the Diaryid is valid Thanks CREATE TABLE diary (id int AUTO_INCREMENT, Narrative text, PRIMARY KEY( id )) CREATE TABLE master ( id int AUTO_INCREMENT, Diaryid int, datemade date, FOREIGN KEY( Diaryid ) REFERENCES diary ( id ), primary key (id)) 所以我现在添加日记记录并且可以有多个主记录,只要 Diaryid 有效 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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