P粉7636623902023-08-19 09:13:10
这是一个快速而简单的SQL示例。我认为没有必要用php来混淆这个概念。只需像处理其他集合一样检索这个集合。
在这个示例中,有很多名字和很多颜色。人们可以有多个喜欢的颜色,而且很多人可以有相同的喜欢的颜色。因此是多对多关系。
***** 表 ********** 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 等等...
这有帮助吗?
P粉8271215582023-08-19 00:58:42
示例场景:大学的学生和课程。一个给定的学生可能参加多门课程,而一门课程通常会有很多学生。
示例表,简单设计:
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