0

I am learning about database, I need to know something about the foreign key in MySQL.

Consider the following two tables.

  1. UserGroupType.
  2. UserGroup.

UserGroupType:

enter image description here

UserGroup:

enter image description here

In this table the foreign key is defined as follows,

foreign key (GroupType_id) references UserGroupType(GroupType_id)

I just want to know whether the name of the field in UserGroup can be changed? consider the following altered statement.

GroupType: enter image description here

foreign key (Type_id) references UserGroupType(GroupType_id)

Is it necessary that both the field names must be same?

How to set the default value for datetime?

Thanks in advance, sorry if it is very basic things.

asked Jul 12, 2013 at 10:13
1
  • 1
    No, it's not necessary for the two column names to be identical. But it's good practice. When you'll have lot of tables and queries with more than 1-2 joins, it helps to have the same name to join. Commented Jul 12, 2013 at 10:18

1 Answer 1

1

foreign key would have a different name from the primary key it is referring to, but necessarily , their data type and other attributes should be the same.
for example , if one is INT(10) unsigned the other should be defined the same.

but sometimes it is a good practice to name them similarly in complex queries. for example when you want to JOIN the relating tables, you can use the syntax :

userGroupType INNER JOIN userGroup USING (GroupType_id)

instead of :

userGroupType INNER JOIN userGroup ON userGroupType.GroupType_id = userGroup.GroupType_id
answered Jul 12, 2013 at 10:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.