Multiple foreign keys in one table to one other table in mysql

元气小坏坏 提交于 2019-12-11 00:22:15

问题


I got two tables in my database: user and call. User exists of 3 fields: id, name, number and call : id, 'source', 'destination', 'referred', date.

I need to monitor calls in my app. The 3 ' ' fields above are actually userid numbers.

Now I'm wondering, can I make those 3 field foreign key elements of the id-field in table user?


回答1:


Yes - you can ;-)

Just define all three foreign keys to refer to the id column in User.




回答2:


Something alike should do the work:

ALTER TABLE call 
ADD CONSTRAINT fk_call_source_user FOREIGN KEY (source) 
REFERENCES user (id)

ALTER TABLE call 
ADD CONSTRAINT fk_call_destination_user FOREIGN KEY (destination) 
REFERENCES user (id) 

ALTER TABLE call 
ADD CONSTRAINT fk_call_referred_user FOREIGN KEY (referred) 
REFERENCES user (id)



回答3:


Alter Table call

ADD FOREIGN KEY (Sourceid) references Source(Id),

FOREIGN KEY (DesId) references Destination(Id)



来源:https://stackoverflow.com/questions/2453731/multiple-foreign-keys-in-one-table-to-one-other-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!