这个问题是我的另一个问题的扩展@需要一些关于在 MySQL 中编码多:多关系的建议和反馈......
我有以下表的 MySQL 代码:
DROP TABLE IF EXISTS `person` ;
CREATE TABLE `person` (
`personID` INT(5) NOT NULL AUTO_INCREMENT ,
`firstName` VARCHAR(50) NOT NULL ,
`lastName` VARCHAR(50) NOT NULL ,
`dateOfBirth` DATE NOT NULL ,
`personType` CHAR(6) NOT NULL,
`photo` BLOB NULL DEFAULT NULL ,
PRIMARY KEY (`personID`))
ENGINE = InnoDB;
SHOW WARNINGS;
DROP TABLE IF EXISTS `parent` ;
CREATE TABLE `parent` (
`parentID` INT(5) NOT NULL,
PRIMARY KEY (`parentID`),
FOREIGN KEY (`parentID`) REFERENCES `person` (`personID`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
SHOW WARNINGS;
DROP TABLE IF EXISTS `player` ;
CREATE TABLE Player (
`playerID` INT(5) NOT NULL,
`motherID` INT(5),
`fatherID` INT(5),
`schoolID` INT(5),
PRIMARY KEY (`playerID`),
FOREIGN KEY (`playerID`) REFERENCES `person` (`personID`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`motherID`) REFERENCES `parent` (`parentID`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`fatherID`) REFERENCES `parent` (`parentID`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`schoolID`) REFERENCES `school` (`schoolID`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
SHOW WARNINGS;
我想格式化查询,使其返回如下信息:
+----------+-----------------+----------------+-----------------+----------------+
| ParentID | ParentFirstName | ParentLastName | PlayerFirstName | PlayerLastName |
+----------+-----------------+----------------+-----------------+----------------+
| 1 | John | Doe | Maggie | Doe |
| 1 | John | Doe | Rob | Doe |
| 2 | Jane | Doe | Rob | Doe |
| 2 | Jane | Doe | Maggie | Doe |
| 3 | Peter | Smith | Neil | Smith |
| 3 | Peter | Smith | Chad | Smith |
| 4 | Mary | Mason | Neil | Smith |
| 4 | Mary | Mason | Chad | Smith |
+----------+-----------------+----------------+-----------------+----------------+
我注意到在上面的可视化中名称重复了好几次,我还想知道使用 GROUP_CONCAT 以某种方式将它们合并在一起是否是个好主意。
我无法以生成所需查询的方式连接这三个表。我在http://sqlfiddle.com/#!2/baf8d找到了我发现的一些灵感(此处由用户提供),但是我无法根据自己的需要定制它(在示例中的第一个和最后一个名称在每个父/玩家表中,而我从 Person 超类继承这些字段。
下面的代码是我在决定在这里提问之前得到的最接近的代码。我想如果我可以将这些查询合并在一起以匹配上面的结果,但我被困住了......
mysql> select person.firstName as ParentFirstName, person.lastName as ParentLastName from person where
-> person.personID IN (select * from parent);
+-----------------+----------------+
| ParentFirstName | ParentLastName |
+-----------------+----------------+
| John | Doe |
| Jane | Doe |
| Peter | Smith |
| Mary | Mason |
+-----------------+----------------+
mysql> select person.firstName as ChildFirstName, person.lastName as ChildLastName from person where
-> person.personID IN (select player.playerID from player);
+----------------+---------------+
| ChildFirstName | ChildLastName |
+----------------+---------------+
| Maggie | Doe |
| Rob | Doe |
| Neil | Smith |
| Chad | Smith |
+----------------+---------------+
我觉得在我的数据库模式中拥有 Person 超类是必要的(因为玩家/父级和其他“人”实体会有类似的细节)而且我宁愿留下它。如果你能帮助我解决这个问题问题我会非常感激。
提前致谢!!