简体   繁体   English

外键mysql

[英]foreign key mysql

I have the following tables: 我有以下表格:

PROFILE table {
user_id INT, 
apitype enum('facebook' , 'main')
}

USER table {
id INT
}

PROFILE.user_id is a foreign key that points to the ID in USER table, but only if PROFILE.apitype = 'main' PROFILE.user_id是指向USER表中ID的外键,但PROFILE.apitype = 'main'

so basically PROFILE.user_id does not refer to an ID in the USER table if PROFILE.apitype != 'main' 所以基本上PROFILE.user_id并不是指一个ID在user表中,如果PROFILE.apitype != 'main'

How can I accomplish this in MYSQL? 如何在MYSQL中完成此操作?

You can probably use a trigger which is fired before insert/update and checks the value of apitype . 您可能可以使用在插入/更新之前触发的触发器 ,并检查apitype的值。 There're even some ways to throw errors in MySQL triggers, eg check this . 甚至还有一些方法可以在MySQL触发器中引发错误,例如,检查this

Well, as this is logic, it should be dealt with in the application, not the database. 好吧,因为这是逻辑,所以应该在应用程序而不是数据库中处理。

You can add the user_id in the profile-table as nullable, making the connection optional, and depending on which storage engine you use you could try triggers (not knowing much about them in mysql though). 您可以在配置表中将user_id添加为可为空,使连接成为可选,并根据您使用的存储引擎尝试触发器(尽管在mysql中对其了解不多)。

I think you cannot accomplish this in an easy way in Mysql. 我认为您无法在Mysql中以简单的方式完成此操作。

For exemple in Postgres you have a check constraint, where you can check if apitype is main then user_id has to be null. 例如在Postgres中,您有一个检查约束,您可以在其中检查apitype是否为main,然后user_id必须为null。

In Mysql you can only do this with trigger and it's not so easy. 在Mysql中,您只能使用触发器执行此操作,但并非如此简单。 I think the easiest way for you and maybe the most reliable is to check it in your application. 我认为对您来说最简单,最可靠的方法就是在您的应用程序中进行检查。 But you can still set a foreign key on user_id even if it's null sometimes 但是您仍然可以在user_id上设置外键,即使有时它为null

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

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