将多个sqlsrv_queries压缩为一个函数

时间:2018-07-10 01:34:27

标签: javascript php mysql sql

我有几个查询,我希望通过创建这样的函数来使其运行更快。最好的方法是什么?这些查询在数据库中找到已维护的票证

public function __select(){}

以下是查询:

 $data = array();
    if($My_Privileges['User_Privilege'] >= 4 && $My_Privileges['Group_Privilege'] >= 4 && $My_Privileges['Other_Privilege'] >= 4){
        $Tickets = array();
        $r = sqlsrv_query($NEI,"
                SELECT   Elev.ID AS ID
                FROM     nei.dbo.Elev 
                         LEFT JOIN nei.dbo.Loc ON Elev.Loc = Loc.Loc
                WHERE    Elev.Status = 0
                         AND Loc.Maint = 1
                GROUP BY Elev.ID

        ;");
        $data2 = array();
        if($r){while($array = sqlsrv_fetch_array($r)){$data2[$array['ID']] = $array;}}
        $sql = array();
        foreach($data2 as $key=>$variable){$sql[] = "Elev.ID = '{$variable['ID']}'";}
        $sql = implode(" OR ",$sql);
        $r = sqlsrv_query($NEI,"
                SELECT   Max(TicketD.EDate) AS Last_Date,
                         Elev.ID            AS ID
                FROM     nei.dbo.TicketD 
                         LEFT JOIN nei.dbo.Elev ON TicketD.Elev = Elev.ID
                         LEFT JOIN nei.dbo.Job  ON TicketD.Job  = Job.ID
                WHERE    Job.Type = 0
                         AND ({$sql})
                GROUP BY Elev.ID

        ;");
        if($r){
            while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
                if(isset($data2[$array['ID']])){
                    $data2[$array['ID']]['Last_Date'] = $array['Last_Date'];
                }
            }
        }
        $r = sqlsrv_query($NEI,"
            SELECT Elev.ID                     AS ID,
                   Elev.State                  AS State, 
                   Elev.Unit                   AS Unit,
                   Elev.Type                   AS Type,
                   Loc.Tag                     AS Location,
                   Zone.Name                   AS Zone,
                   Emp.fFirst + ' ' + Emp.Last AS Route
            FROM   nei.dbo.Elev
                   LEFT JOIN nei.dbo.Loc   ON Elev.Loc   = Loc.Loc
                   LEFT JOIN nei.dbo.Zone  ON Loc.Zone   = Zone.ID
                   LEFT JOIN nei.dbo.Route ON Loc.Route  = Route.ID
                   LEFT JOIN nei.dbo.Emp   ON Route.Mech = Emp.fWork
            WHERE  Loc.Maint = 1
                   AND ({$sql})
        ;");
        if($r){
            while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
                $array['Last_Date'] = substr($data2[$array['ID']]['Last_Date'],0,10);
                $data[] = $array;
            }
        }
    }

在另一个PHP文件中,我正在创建一个名为__select()的函数,并且我一直在尝试寻找最佳方法来压缩查询并使网站运行更快。任何帮助将不胜感激。

0 个答案:

没有答案