I haven't found any MYSQL many-to-many relationships examples here and in google. What I am looking is to see a very simple example with php+mysql showing database's results. Can anybody write a very simple example?
5 Answers
Example scenario: students and courses at a university. A given student might be on several courses, and naturally a course will usually have many students.
Example tables, simple design:
CREATE TABLE `Student` (
`StudentID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(25),
`LastName` VARCHAR(25) NOT NULL,
PRIMARY KEY (`StudentID`)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci
CREATE TABLE `Course` (
`CourseID` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`Code` VARCHAR(10) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
`Name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`CourseID`)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci
CREATE TABLE `CourseMembership` (
`Student` INT UNSIGNED NOT NULL,
`Course` SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (`Student`, `Course`),
CONSTRAINT `Constr_CourseMembership_Student_fk`
FOREIGN KEY `Student_fk` (`Student`) REFERENCES `Student` (`StudentID`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Constr_CourseMembership_Course_fk`
FOREIGN KEY `Course_fk` (`Course`) REFERENCES `Course` (`CourseID`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB CHARACTER SET ascii COLLATE ascii_general_ci
Find all students registered for a course:
SELECT
`Student`.*
FROM
`Student`
JOIN `CourseMembership` ON `Student`.`StudentID` = `CourseMembership`.`Student`
WHERE
`CourseMembership`.`Course` = 1234
Find all courses taken by a given student:
SELECT
`Course`.*
FROM
`Course`
JOIN `CourseMembership` ON `Course`.`CourseID` = `CourseMembership`.`Course`
WHERE
`CourseMembership`.`Student` = 5678
-
1
-
2Can you please add how to properly insert data? In which order etc. Jan 11, 2020 at 2:28
-
Is there any way to update the record in this case? What i'm doing now is to delete the existing record and add new in update case? How can i check that which record to be updated? Sep 23, 2021 at 9:55
Here's a quick and dirty example of the SQL involved. I don't see any need to muddy up the concept with php. Just retrieve the set like you would any other.
In this example, there are many names, and many colors. People are allowed to have more than one favorite color, and many people can have the same favorite color. Hence many to many.
***** Tables **********
person
--------
id - int
name - varchar
favColor
-------------
id - int
color - varchar
person_color
------------
person_id - int (matches an id from person)
color_id - int (matches an id from favColor)
****** Sample Query ******
SELECT name, color
FROM person
LEFT JOIN person_color ON (person.id=person_id)
LEFT JOIN favColor ON (favColor.id=color_id)
****** Results From Sample Query *******
Name - Color
---------------
John - Blue
John - Red
Mary - Yellow
Timmy - Yellow
Suzie - Green
Suzie - Blue
etc...
Does that help?
mysql> SELECT * FROm products;
+----+-----------+------------+
| id | name | company_id |
+----+-----------+------------+
| 1 | grechka | 1 |
| 2 | rus | 1 |
| 3 | makaronu | 2 |
| 4 | yachna | 3 |
| 5 | svuniacha | 3 |
| 6 | manka | 4 |
+----+-----------+------------+
6 rows in set (0.00 sec)
mysql> SELECT * FROm company;
+----+----------+
| id | name |
+----+----------+
| 1 | LVIV |
| 2 | KIEV |
| 3 | KHarkiv |
| 4 | MADRID |
| 5 | MILAN |
| 6 | KOR |
+----+----------+
6 rows in set (0.00 sec)
mysql> SELECT * FROm many_many;
+------------+---------+
| product_id | city_id |
+------------+---------+
| 1 | 1 |
| 1 | 3 |
| 2 | 3 |
| 1 | 2 |
| 1 | 4 |
| 2 | 4 |
| 2 | 1 |
| 3 | 1 |
+------------+---------+
8 rows in set (0.00 sec)
mysql> SELECT products.name,company.name FROM products JOIN many_many ON many_
ny.product_id =products.id JOIN company ON company.id= many_many.city_id;
+----------+---------+
| name | name |
+----------+---------+
| grechka | LVIV |
| grechka | KHarkiv |
| grechka | KIEV |
| grechka | MADRID |
| rus | KHarkiv |
| rus | MADRID |
| rus | LVIV |
| makaronu | LVIV |
+----------+---------+
8 rows in set (0.00 sec)
SELECT a.a_id, b.b_id, b.b_desc,
CASE WHEN x.b_id IS NULL THEN 'F' ELSE 'T' END AS selected
FROM a
CROSS JOIN b
LEFT JOIN x ON (x.a_id = a.a_id AND x.b_id = b.b_id)
WHERE (a.a_id = 'whatever')
-
12
you can use many-to-many relationship, using a junction table.
CREATE TABLE Student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE Course (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE Student_Course (
student_id INT NOT NULL,
course_id INT NOT NULL,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Student(id),
FOREIGN KEY (course_id) REFERENCES Course(id)
);
INSERT INTO Student (name) VALUES ('Mike');
INSERT INTO Student (name) VALUES ('Jack');
INSERT INTO Student (name) VALUES ('Henry');
INSERT INTO Course (name) VALUES ('Math');
INSERT INTO Course (name) VALUES ('Science');
INSERT INTO Course (name) VALUES ('History');
INSERT INTO Student_Course (student_id, course_id) VALUES (1, 1);
INSERT INTO Student_Course (student_id, course_id) VALUES (1, 2);
INSERT INTO Student_Course (student_id, course_id) VALUES (2, 2);
INSERT INTO Student_Course (student_id, course_id) VALUES (2, 3);
INSERT INTO Student_Course (student_id, course_id) VALUES (3, 1);
INSERT INTO Student_Course (student_id, course_id) VALUES (3, 2);
INSERT INTO Student_Course (student_id, course_id) VALUES (3, 3);
Establishing a many-to-many relationship between the tables in a database is usually done for ensuring efficient data processing and data integrity, as well as for database normalization and data analysis tasks.
Since relational databases don’t allow implementing a direct many-to-many relationship between two tables, handling that kind of relationship can be an intimidating task.
When you need to establish a many-to-many relationship in relational database between two or more tables, the simplest way is to use a Junction Table.
A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table. So, that’s a junction table in a nut shell.
-
Please add some explanation to your answer such that others can learn from it. How does your example differ from the others that were shared years ago? Jan 26 at 8:45