多对多关系示例

2022-08-30 11:17:25

我在这里和谷歌中没有找到任何MYSQL多对多关系的例子。我想要的是看到一个非常简单的例子,其中php + mysql显示了数据库的结果。任何人都可以写一个非常简单的例子吗?


答案 1

示例场景:大学的学生和课程。一个给定的学生可能在几门课程上,当然,一门课程通常会有很多学生。

示例表,简单设计:

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

查找注册课程的所有学生:

SELECT
    `Student`.*
FROM
    `Student`
    JOIN `CourseMembership` ON `Student`.`StudentID` = `CourseMembership`.`Student`
WHERE
    `CourseMembership`.`Course` = 1234

查找给定学生参加的所有课程:

SELECT
    `Course`.*
FROM
    `Course`
    JOIN `CourseMembership` ON `Course`.`CourseID` = `CourseMembership`.`Course`
WHERE
    `CourseMembership`.`Student` = 5678

答案 2

下面是所涉及的 SQL 的快速而肮脏的示例。我认为没有必要用php来混淆这个概念。只需像检索其他任何集合一样检索该集合即可。

在此示例中,有许多名称和许多颜色。人们被允许拥有多种喜欢的颜色,许多人可以拥有相同的喜欢的颜色。因此,很多到很多。


***** 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...

这有帮助吗?


推荐