Setting up foreign key with different datatype

后端 未结 1 435
梦谈多话
梦谈多话 2020-12-07 02:20

If I create two tables and I want to set one column as foreign key to another table column why the hell am I allowed to set foreign key column datatype?

相关标签:
1条回答
  • 2020-12-07 02:47

    Actually it does make sense here is why:

    In a table, you can in fact set any column as its primary key. So it could be integer, double, string, etc. Even though nowadays, we mostly use either integers or, more recently, strings as primary key in a table.

    Since the foreign key is pointing to another table's primary key, this is why you need to specify the foreign key's datatype. And it obviously needs to be the same datatype.

    EDIT:

    SQL implementations are lax on this case as we can see: they do allow compatible types (INT and BIG INT, Float or DECIMAL and DOUBLE) but at your own risk. Just as we can see in your example, below.

    However, SQL norms do specify that both datatypes must be the same. If datatype is character, they must have the same length, otherwise, if it is integer, they must have the same size and must both be signed or both unsigned.

    You can see by yourself over here, a chapter from a MySQL book published in 2003.

    Hope this answers your question.

    0 讨论(0)
提交回复
热议问题