希望您一切顺利,我想发布一个问题,找出使用计数和子查询将以下SQL转换为Eloquent的最佳方法:
SELECT pkgCnt.holiday_type_desc, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading
) pkgCnt
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.holiday_type_id;
和
SELECT country_name, 0
FROM country
WHERE country_id NOT IN (
SELECT country_id
FROM package
)
UNION ALL
SELECT pkgCnt.country_name, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT country_name, package_heading
FROM package pkg
LEFT JOIN country cnty ON pkg.country_id = cnty.country_id
GROUP BY pkg.country_id, package_heading
) pkgCnt
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.country_id;
答案 0 :(得分:0)
最后我决定使用存储过程路由而不是使用Eloquent和raw,所以这是我的最终工作代码:
包和特价模型
public function count($is_holiday_type = false) {
$result = DB::select("CALL package_count(?)", array($is_holiday_type));
return $result;
}
MySQL存储过程:
DELIMITER //
CREATE PROCEDURE package_count (IN is_holiday_type TINYINT(1))
BEGIN
IF is_holiday_type = 1
THEN
SELECT pkgCnt.holiday_type_desc, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading
) AS pkgCnt
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.holiday_type_id
ORDER BY pkg.holiday_type_id;
ELSE
SELECT country_name, 0 AS count
FROM country
WHERE country_id NOT IN (
SELECT country_id
FROM package
)
UNION ALL
SELECT pkgCnt.country_name, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT country_name, package_heading
FROM package pkg
LEFT JOIN country cnty ON pkg.country_id = cnty.country_id
GROUP BY pkg.country_id, package_heading
) AS pkgCnt
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.country_id
ORDER BY country_name;
END IF;
END //
DELIMITER ;