我有一个查询,出于性能原因我需要使用STRAIGHT_JOIN。查询构建如下:
$query->join('tbl2 as b', function ($join) {
$join->on('a.b_id', '=', 'b.id')
->where('b.x_id', $x);
})
有没有办法强制查询使用STRAIGHT_JOIN?看起来这是不可能的,因为没有空间(就像你有INNERT JOIN,LEFT JOIN等)。
答案 0 :(得分:2)
不,这是不可能的。
在编译SQL时,Laravel硬编码了连接类型和JOIN
关键字之间的空格,所以,就像你说的那样,无法说服它使用STRAIGHT_JOIN
。见Illuminate\Database\Query\Grammars\Grammar::compileJoins()
:
$sql[] = "$type join $table on $clauses";
您必须run a raw query。
答案 1 :(得分:0)
我们可以对STRAIGHT_JOIN使用addSelect方法。但是我们还需要小心,以避免不必要的反引号(`)和逗号(,)。
SQL查询:
SELECT STRAIGHT_JOIN
employee.salary as `e.salary`,
...
...
FROM employee
LEFT JOIN department
ON employee.dept_id = department.id
LEFT JOIN projects
ON employee.project_id = project.id
LEFT JOIN ...
ON ...
WHERE
employee.doj BETWEEN (start_date, end_date)
AND ....
OR ....
ORDER BY employee.dob ASC;
代码:
protected function addStraightJoinUsingSelectFields()
{
$selectFields = $this->getSelectFields(); // get select fields array
$firstFieldArray = explode(' AS ', $selectFields[0]); // get the 0th element and split on ' AS '.
// "employee.salary AS e.salary" => array([0] => "employee.salary", [1] => "e.salary")
$firstFieldArray[1] = '`' . trim($firstFieldArray[1], '`') . '`'; // "`e.salary`"
$firstFieldString = implode($firstFieldArray, ' AS '); // "employee.salary AS `e.salary`"
$straightJoinColumn = 'straight_join ' . $firstFieldString; // "straight_join employee.salary AS `e.salary`"
$selectFields[0] = \DB::raw($straightJoinColumn);
foreach ($selectFields as $fieldToSelect)
{
$this->query->addSelect($fieldToSelect);
}
}
答案 2 :(得分:-1)
似乎SELECT STRAIGHT_JOIN <cols> ...
解决了这个问题。这可以通过操作要选择的列列表相对容易地完成,并自动应用于查询中的所有联接。