Laravel SQL查询返回错误的结果

时间:2017-02-21 05:17:49

标签: php mysql laravel-5 laravel-5.1

我在Laravel查询构建器

中有这个SQL查询
$this->candidate->select('candidates.*', 'candidates.id as candidate_id', 'mj.interviewScheduledDate')
            ->join('candidates_positions', 'candidates_positions.candidate_id', '=', 'candidates.id')
            ->leftJoin(DB::raw("(SELECT mat1.* FROM matches AS mat1
                                    JOIN (SELECT candidate_id, MAX(id) AS id FROM matches GROUP BY candidate_id) 
                                    AS mat2 ON mat1.candidate_id = mat2.candidate_id AND mat1.id = mat2.id)
                                    AS mj"), function ($join) {
                $join->on("candidates.id", "=", "mj.candidate_id");
            })
            ->where(function ($query) {
                $query->where("mj.stage", "<", "4")
                    ->whereNull('mj.stage', "or");
            })
            ->groupBy('candidates.id')

            ->paginate(Config::get('match.pagination'));

这将返回错误的结果,其中来自同一“查询”构建器的“生成的”查询返回正确的结果。 $candidate->toSql()返回以下查询。甚至尝试删除group by语句。它没有帮助

SELECT
      `candidates`.*,
      `candidates`.`id` AS `candidate_id`,
      `mj`.`interviewScheduledDate`
    FROM `candidates`
      INNER JOIN `candidates_positions` ON `candidates_positions`.`candidate_id` = `candidates`.`id`
      LEFT JOIN (SELECT mat1.*
                 FROM matches AS mat1
                   JOIN (SELECT
                           candidate_id,
                           MAX(id) AS id
                         FROM matches
                         GROUP BY candidate_id)
                     AS mat2 ON mat1.candidate_id = mat2.candidate_id AND mat1.id = mat2.id)
        AS mj ON `candidates`.`id` = `mj`.`candidate_id`
    WHERE (`mj`.`stage` < ? OR `mj`.`stage` IS NULL)
    GROUP BY `candidates`.`id`
    LIMIT 10 OFFSET 0

正确的结果 enter image description here

Laravel返回结果 enter image description here

1 个答案:

答案 0 :(得分:1)

仔细检查如何绑定值。您可能会绑定与Laravel不同的值。

此链接也很有用:Different results using same query with DB::raw and Eloquent