***** 表 **********
person
--------
id - int
name - varchar
favColor
-------------
id - int
color - varchar
person_color
------------
person_id - int (与person中的id匹配)
color_id - int (与favColor中的id匹配)
****** 示例查询 ******
SELECT name, color
FROM person
LEFT JOIN person_color ON (person.id=person_id)
LEFT JOIN favColor ON (favColor.id=color_id)
****** 示例查询的结果 *******
Name - Color
---------------
John - Blue
John - Red
Mary - Yellow
Timmy - Yellow
Suzie - Green
Suzie - Blue
等等...
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
這是一個快速而簡單的SQL範例。我認為沒有必要用php來混淆這個概念。只需像處理其他集合一樣檢索這個集合。
在這個範例中,有很多名字和很多顏色。人們可以有多個喜歡的顏色,而且很多人可以有相同的喜歡的顏色。因此是多對多關係。
這有幫助嗎?
範例場景:大學的學生和課程。一個給定的學生可能參加多門課程,而一門課程通常會有很多學生。
範例表,簡單設計:
找出註冊了某門課程的所有學生:
找出某個特定學生參加的所有課程: