A
A
Anton Dyshkant2015-04-08 11:49:59
MySQL
Anton Dyshkant, 2015-04-08 11:49:59

Should I set DEFAULT or NULL for FOREIGN KEY in MySQL?

Hello!
I have three tables cascading from each other:
table_1:

  • id
  • t2_id
  • other_fields
table_2:
  • id
  • t3_id
  • other_fields
table_3:
  • id
  • other_fields

Those. the result is:
`table_1`.`t2_id` <-- `id`.`table_2`
`table_2`.`t3_id` <-- `id`.`table_3`,
where "<--" indicates the relationship "many to alone."
Actually, the essence of the question: at the moment, the fields t2_id and t3_id are quite ordinary: not NULL, default: none. At the same time, in a number of cases I have seen that FOREIGN KEY fields are set to default: 0, and also heard that they are sometimes set to NULL.
Actually, I wanted to clarify why this is necessary, because at the same time in the table where the value is taken from by the key, there is no row with an id equal to zero. Is it worth specifying default/NULL values ​​when creating foreign keys?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-04-08
@vyshkant

This, oddly enough, depends on whether the field that stores the binding is required to be filled. If it is mandatory (that is, the ratio is 1 to 1), then neither the default value nor nullable should be specified. If not required (ratio 0 to 1 or 1 to 1), then you can specify a default value or a nullable flag.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question