简体   繁体   English

设置外键的默认值?

[英]Setting default value of foreign key?

I have three tables in database: 我在数据库中有三个表:

user (user_id(pk), username, email, password, country_code(fk), city_id(fk));

country (country_code(pk), country name);

city (city_id(pk), city_name);

Country and city tables are already filled with details. 国家和城市表格已经填充了详细信息。 user table is blank. 用户表是空白的。 All table has default value 'none' for each record. 对于每条记录,所有表都具有默认值“none”。

And I have a simple interface which asks for email and password for registration. 我有一个简单的界面,要求注册电子邮件和密码。

So, when user enters the email and password, the mysql does not allow to insert. 因此,当用户输入电子邮件和密码时,mysql不允许插入。 It shows following error: 它显示以下错误:

Cannot add or update a child row: a foreign key constraint fails

This is because user table can not insert any values for country_code and city_id that are not in country and city table. 这是因为user表不能插入country_codecity_id中不在countrycity表中的任何值。 And user has not yet given the value, the default value is none, which is not in both parent tables. 并且用户尚未给出值,默认值为none,这两个父表中都没有。

So, How to deal with integrity? 那么,如何处理诚信? Should I give NULL as the default value of both foreign keys in child table(which is user )? 我应该将NULL作为子表( user )中两个外键的默认值吗? I tried giving default values NULL and it is working. 我尝试给出默认值NULL并且它正在工作。 I want to know that if it won't make any trouble for integrity issues in my database design? 我想知道,如果它不会对我的数据库设计中的完整性问题造成任何麻烦? Is it a proper way? 这是一种正确的方式吗?

With these design you could simply add a ' (none) ' record for tables country and city . 通过这些设计,您只需为表countrycity添加“ (无) ”记录即可。

This way you'd have two " magic values ", country_code and city_id related to this ' (none) ' records, to be used as default values of country_code(fk) , city_id(fk) in new entries of user table. 这样,您就有两个“ 魔术值 ”, country_codecity_id与这个' (无) '记录相关,在用户表的新条目中用作country_code(fk)city_id(fk)的默认值。

You could also avoid " magics " (i mean constant values of a special meaning) for country_code and city_id only hard-wiring ' (none) ' value for both country_name and city_name and selecting the corresponding primary keys by mean of a where criteria on country_name and city_name . 您还可以为country_codecity_id避免“ magics ”(我的意思是特殊含义的常量值),只为country_namecity_name选择硬连线' (none) '值,并通过country_name上的where条件选择相应的主键和city_name

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

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