以结构化方式显示联接的mysql数据,而不会丢失性能

时间:2012-06-08 11:27:42

标签: php mysql performance database-performance

在db中,有项目。每个项目都有文件。每个文件都有多个版本。

所以理论上,我可以这样做(伪);

$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";

但是,现在,这给我留下了非结构化数据:

enter image description here

所以我做的是:

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";
        }
    }
}

给出了输出:

ex2

但是我不确定我是否正在获得任何性能这样做,因为在连接的行中有很多重复的数据,并且确实有很多工作来更新代码一次/如果db中的东西变化。

我想简而言之;这只是一个肮脏的解决方案,我认为是一个适当的解决方案。

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:3)

无法直接从MySQL数据库返回结构化数据。您将这些面向表的数据转换为数组的努力是正确的。

查看PHP dibi library->fetchAssoc()方法(doc),它可以用简短的语法完成您所需的一切。