I have 2 tables, User
and Employee
. Each user is given a User_ID
and that is a primary key in the User
table and a foreign key in the Employee
table. Can that attribute in the Employee
table also be a primary key?
相关问题
- NOT DISTINCT query in mySQL
- Flush single app django 1.9
- keeping one connection to DB or opening closing pe
- Mysql-installer showing error : Memoy could not be
- Android Room Fetch data with dynamic table name
相关文章
- Connection pooling vs persist connection mysqli
- Speed up sqlFetch()
- How Do I Seed My Database in the setupBeforeClass
- I set a MySQL column to “NOT NULL” but still I can
- Where in Django can I run startup code that requir
- Google OAuth 2.0 User id datatype for MYSQL
- How to find if a referenced object can be deleted?
- EntityFramework 6 AddOrUpdate not working with com
If you have a one-to-one relation between two tables, then the primary key of the details table is a foreign key as well.
If you have a m-to-n relation, the junction table has columns relating to the two primary keys of the m and the n-tables. These columns are primary keys and foreign keys at the same time.
Note that with this construction, a record of one table can only be linked to a specific record of the other table once, since each composite primary key of the junction table must be unique. If you want to allow non-unique pairings, define a separate primary key in the junction table:
In this case, the primary key and foreign key constraints are set on different columns. Alternatively you can also build the primary key with the two foreign keys plus one numerator or another discerning attribute.
In your case, if there is a one-to-one or a one-to-zero-or-one relationship between
User
andEmployee
, then yes, theUser_ID
in theEmployee
table can be Foreign Key (FK) and Primary Key (PK) at the same time. In words, this would mean: A user can be an employee as well, in which case the employee data would be attached to the user. If he is not an employee (he could be an external expert), no employee record is attached. IfUser_ID
is FK and PK inEmployee
, each user can have at most one employee record attached. IfUser_ID
was only FK but not PK in tableEmployee
then a user could have several related employee records.Yes. You would do this for instance if you wanted to enforce that all employees are users, and some users can be employees. This would be (zero or one) to one relationship.
Otherwise, you would not normally have the primary key the same as the foreign key, although it could contain foreign key(s), as in the case of a junction table for a many to many relationship.