使用Laravel中的存储过程在MYSQL中返回多个结果集

时间:2018-02-04 14:35:31

标签: php mysql stored-procedures laravel-5

我已经六次执行查询以返回多个结果集。所有调用的查询都相同,但参数只有不同。它如下:

public function getGroupedInfo($id, $type, $zip,  $field) {

    return DB::table('data')
             ->select(DB::raw("{$field} as obj, COUNT(*) as count"))
             ->where('report_id', $id)
             ->where('book_section', $type)
             ->where('zip_code', $zip)
             ->groupBy("{$field}")
             ->orderBy('count', 'DESC')->get();

}

我按如下方式调用该函数:

public function stats(Request $request){
    $schools['Elementary Schools'] = $this->getGroupedInfo($id, $listing_type, $zip_code, 'elementary_school');
    $schools['Middle Schools'] = $this->getGroupedInfo($id, $listing_type, $zip_code, 'middle_school');
    $schools['High Schools'] = $this->getGroupedInfo($id, $listing_type, $zip_code, 'high_school');
    $others['lot_sqft'] = $this->getGroupedInfo($id, $listing_type, $zip_code, 'lot_sqft');
}

我计划将它们添加到单个存储过程中,但我不确定如何在单个存储过程中编写这些内容,然后在Laravel结束时使用结果。

你能帮我解决这个问题。提前致谢。

1 个答案:

答案 0 :(得分:1)

由于您始终在查询相同的四个字段的计数,因此您可以使用SELECT写下包含四个UNION语句的存储过程,如下所示:

CREATE PROCEDURE GetCounts
(
    IN ReportId INT,
    IN ListingType VARCHAR(100),
    IN ZipCode INT
)
BEGIN
    SELECT 'elementary_school' AS type, elementary_school AS obj, COUNT(*) AS count
    FROM data
    WHERE report_id = @ReportId AND book_section = @ListingType AND zip_code = @ZipCode
    GROUP BY elementary_school
    ORDER BY count DESC

    UNION

    SELECT 'middle_school' AS type, middle_school AS obj, COUNT(*) AS count
    FROM data
    WHERE report_id = @ReportId AND book_section = @ListingType AND zip_code = @ZipCode
    GROUP BY middle_school
    ORDER BY count DESC

    UNION

    SELECT 'high_school' AS type, high_school AS obj, COUNT(*) AS count
    FROM data
    WHERE report_id = @ReportId AND book_section = @ListingType AND zip_code = @ZipCode
    GROUP BY high_school
    ORDER BY count DESC

    UNION

    SELECT 'lot_sqft' AS type, lot_sqft AS obj, COUNT(*) AS count
    FROM data
    WHERE report_id = @ReportId AND book_section = @ListingType AND zip_code = @ZipCode
    GROUP BY lot_sqft
    ORDER BY count DESC
END;

然后,您可以按如下方式调用它:

DB::select('EXEC GetCounts(?,?,?)', array($id, $listing_type, $zip_code));