显示排序数据

时间:2013-03-19 21:21:16

标签: php html sorting

我在尝试正确格式化数据时遇到了问题。

首先,我的PHP代码如下所示(有关演示,请参阅JSFiddle):

$result_rules = $db->query("SELECT rules.source_id, rules.destination_id, dest.project AS dest_project, src.project AS src_project, src.pk_id AS src_id, excep.project AS excep_project, excep.feature AS excep_feature, excep.milestone AS excep_milestone
    FROM dbo.FFC_Rules rules
    INNER JOIN dbo.Destination dest
        ON dest.pk_id=rules.destination_id
    LEFT JOIN dbo.Source src
        ON src.pk_id=rules.source_id
    LEFT JOIN dbo.Exceptions excep
        ON src.pk_id=excep.source_id
    ORDER BY dest.project ASC");

$last_src = false;
$last_dest = false;
while($row = sqlsrv_fetch_array($result_rules)){  
    if ($row['dest_project'] !== $last_dest) {
        if ($last_dest !== false)
            echo "</div>";
        $last_dest = $row['dest_project'];
        echo "<div class='projectscontainer'>";
        echo    "<div id='arrow' class='arrow-right'></div>";
        echo    "<span class='item destproject unselectable' title='ID: $row[destination_id]'>$row[dest_project]</span>";
        echo    "<br>";
    }

    echo        "<div class='srcprojects'>";
    if (is_null($row['src_id'])) {
        echo        " Source ID for Destination ID $row[destination_id] is NULL";
    } else {
        if($row['src_project'] !== $last_src) {
            $last_src = $row['src_project'];
            echo    "<span class='item srcproject' title='ID: $row[src_id]'>$row[src_project]</span>";
            if (!is_null($row['excep_feature']))
                echo"<div id='arrow' class='arrow-right'></div><span class='item srcproject exception' title='Feature'>$row[excep_feature]</span>";
            if (!is_null($row['excep_milestone']))
                echo"<div id='arrow' class='arrow-right'></div><span class='item srcproject exception' title='Milestone'>$row[excep_milestone]</span>";
            echo    "<br>";
        }
    }
    echo        "</div>";//end srcprojects
}
echo        "</div>";//end projectscontainer

在我的查询中,我按目标项目排序,并在我的PHP代码中检查当前dest是否与最后一个相同。如果是这样,我不会显示名称。我想对Source项目执行相同的操作,但由于查询是按Destination项目排序的,因此重复发生在不同的地方,并且不会被我的PHP代码捕获。

如何在不必再次获取查询返回的所有40,000多行的情况下完成此操作?

1 个答案:

答案 0 :(得分:0)

你必须在另一个中排序,如:

ORDER BY dest.project ASC,src.project ASC

并使用LIMIT子句来说明您希望从查询中获得多少行。