简体   繁体   中英

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.

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. 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. And user has not yet given the value, the default value is none, which is not in both parent tables.

So, How to deal with integrity? Should I give NULL as the default value of both foreign keys in child table(which is user )? I tried giving default values NULL and it is working. 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 .

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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