在数据库中,有项目。每个项目都有文件。每个文件都有多个版本。
所以理论上,我可以做到这一点(伪);
$res = mysql_query("SELECT * FROM projects");
while($row=mysql_fetch_assoc($res))
{
echo "Project ".$row["id"]."<br/>";
$res2 = mysql_query("SELECT * FROM projectfiles");
while($row2=mysql_fetch_assoc($res2))
{
echo "FileID ".$row2["id"]."<br/>";
$res3 = mysql_query("SELECT * FROM fileversions");
while($row3=mysql_fetch_assoc($res3))
{
echo $row3["name"]."<br/>";
}
echo "<br/>";
}
}
样本输出:
Project 1
FileID 1
test_file_1.txt.1
FileID 2
test_file_2.txt.1
FileID 3
test_file_3.txt.1
test_file_3.txt.2
但这将意味着只需要一个的负载和负载 mysql 查询。
所以我加入了查询:
$sql = "SELECT projectfiles.*, fileversions.*,
projects.id as projects_id
FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
$sql .= " LEFT JOIN".
" (SELECT
fileversions.id as fileversions_id,
fileversions.name as fileversions_name,
fileversions.location as fileversions_location,
fileversions.fileID as fileversions_fileID
FROM fileversions
) AS fileversions".
" ON projectfiles.projectfiles_fileID = fileversions_fileID";
但是现在,当然,这给我留下了非结构化数据:
所以我所做的是:
while($row = mysql_fetch_assoc($res))
{
$projectID = $row["projects_id"];
$fileID = $row["projectfiles_fileID"];
$fileversionID = $row["fileversions_id"];
$fileversionsArray[$fileversionID] = array($row["fileversions_name"],$row["fileversions_location"]);
$fileArray[$fileID][$fileversionID] = $fileversionID;
$projectArray[$projectID][$fileID] = $fileID;
}
所以我可以像这样展示它:
foreach($projectArray as $projectID => $projectDatas)
{
echo "Project ID: ".$projectID."\n";
foreach($projectDatas as $fileID)
{
echo "\tFile ID: ".$fileID."\n";
foreach($fileArray[$fileID] as $fileversionID)
{
echo "\t\tFile version name: ";
echo $fileversionsArray[$fileversionID][0];
echo "\n";
echo "\t\tFile location: ";
echo $fileversionsArray[$fileversionID][2];
echo "\n";
}
}
}
这给出了输出:
但是我不太确定这样做是否能获得任何性能,因为在连接的行中有很多重复的数据,而且如果数据库中的内容发生变化,更新一次代码肯定需要做很多工作。
我想简而言之;对于我认为存在的正确解决方案,这感觉就像是一种肮脏的解决方法。
有没有更好的解决方案?