PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 8, 2022

[FIXED] Many to One relationship?

 March 08, 2022     mysql, one-to-many, php, yii     No comments   

Issue

The following MySQL code...

CREATE TABLE Employee (
    id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    departmentId TINYINT UNSIGNED NOT NULL
        COMMENT "CONSTRAINT FOREIGN KEY (departmentId) REFERENCES Department(id)",
    firstName VARCHAR(20) NOT NULL,
    lastName VARCHAR(40) NOT NULL,
    email VARCHAR(60) NOT NULL,
    ext SMALLINT UNSIGNED NULL,
    hireDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    leaveDate DATETIME NULL,
    INDEX name (lastName, firstName),
    INDEX (departmentId)
)

CREATE TABLE Department (
    id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    name VARCHAR(40),
    UNIQUE (name)
)

... defines a many to one relationship between an employee and a department. In other words, an employee can only be in one department, but a department can have many employees. But can someone explain this in more detail? How does the above code tell me that?


Solution

It is sometimes easy to discern the relationship between two (or more) tables by looking at the foreign key of referring table.

A simple rule is, if the foreign key is a primary key itself in its own table, the relationship is probably 1 to 1, whereas if the foreign key is not a primary key in its own table, the relationship is probably 1 to many, where the table having the foreign key at the "many" end.

In your example, for departmentID in Employee, it is not a primary key. Therefore, in this situation, a Department can be referenced by a lot of Employees at the same time, hence the "1 to many" relation can be established.

However, in your quoted example from mkyong.com, both tables (stock and stock_detail) use stock_id as primary key. In this situation, the "1 to 1" relation can be established.

Consider this: Both stock and stock_detail tables will only contain ONE single record having a certain value as stock_id. I made a sample here.



Answered By - Amao Mao
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing