和我的预期结果
-------------------------------------------------------------
| doc_id | document_name | requirement_id |requirement_name |
-------------------------------------------------------------
| 1 |Certifications | 3 | requirementname |
| | | 1 | requirementname |
| | | 7 | requirementname |
| | | 9 | requirementname |
| 2 |CAV | 1 | requirementname |
| | | 4 | requirementname |
| | | 3 | requirementname |
| | | 5 | requirementname |
-------------------------------------------------------------
使用PHP在HTML中显示是否可以输出?有人可以告诉我怎么做? 这与外键和连接表有关吗? 提前谢谢。
答案 0 :(得分:0)
为这些问题构建sqlfiddle会很有帮助,以便审阅者可以跟随公共架构/数据集。给出以下架构:
CREATE TABLE `document` (
`document_id` INT(11) PRIMARY KEY AUTO_INCREMENT,
`document_name` VARCHAR(64) DEFAULT NULL,
`document_amount` INT(4),
`requirement1` INT(11) DEFAULT 0,
`requirement2` INT(11) DEFAULT 0,
`requirement3` INT(11) DEFAULT 0,
`requirement4` INT(11) DEFAULT 0,
`requirement5` INT(11) DEFAULT 0,
`requirement6` INT(11) DEFAULT 0,
`requirement7` INT(11) DEFAULT 0
);
CREATE TABLE `requirement` (
`requirement_id` INT(11) PRIMARY KEY AUTO_INCREMENT,
`document_id` INT(11) DEFAULT 0,
`requirement_name` VARCHAR(64) DEFAULT NULL
);
主要障碍是每个文件的要求都是非标准化的;每个文档列可能有多达7种不同的需求选项。为了实现这一点,您需要将它们组合在一起,使它们代表一个列,这可以通过union来完成:
SELECT `document_id`, `requirement1` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement2` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement3` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement4` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement5` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement6` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement7` as 'requirement' FROM `document`
然后,您可以将查询连接到所需的结果集:
SELECT d.document_id, d.document_name, r.requirement_id, r.requirement_name FROM
`document` as `d` JOIN
(
# correct for non-normalization via UNION on requirements
SELECT `document_id`, `requirement1` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement2` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement3` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement4` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement5` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement6` as 'requirement' FROM `document`
UNION
SELECT `document_id`, `requirement7` as 'requirement' FROM `document`
) `req`
ON d.document_id = req.document_id
JOIN `requirement` as `r`
ON req.requirement = r.requirement_id
WHERE req.requirement > 0
ORDER BY d.document_id, r.requirement_id;