[英]Return multiple result sets in MYSQL using stored procedure in Laravel
I'm preforming a query six times to return me multiple result sets.我正在执行六次查询以返回多个结果集。 The query is same for all call but the params only vary.
所有调用的查询都相同,但参数仅有所不同。 It is as follows:
如下:
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();
}
I'm calling the function as follows:我按如下方式调用该函数:
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');
}
I was planning on adding them to a single stored procedure, but I'm not sure how to write these in a single stored procedure and then work with the results on Laravel end.我打算将它们添加到单个存储过程中,但我不确定如何在单个存储过程中编写这些,然后在 Laravel 端处理结果。
Can you please help me out on this.你能帮我解决这个问题吗? Thanks in advance.
提前致谢。
Since you are always querying the count of the same four fields, you can write down a stored procedure with four SELECT
statements concatenated using UNION
, as follows:由于您总是在查询相同的四个字段的计数,因此您可以写下一个带有使用
UNION
连接的四个SELECT
语句的存储过程,如下所示:
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;
Then, you can call it as follows:然后,您可以按如下方式调用它:
DB::select('EXEC GetCounts(?,?,?)', array($id, $listing_type, $zip_code));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.