简体   繁体   English

此MySQL查询与Laravel查询生成器等效吗?

[英]What is the equivalent of this MySQL query to Laravel Query Builder?

This is my query from MySQL. 这是我从MySQL查询。 I want to use 'LEFT JOIN' to two same tables with different aliases and having an 'ON' that has 'AND' inside its parenthesis. 我想对两个具有不同别名的相同表使用'LEFT JOIN',并在其括号内使用'AND'的'ON'。 And this query arrives with the correct results, but my problem is how can I know the equivalent of this query to its Laravel query? 并且此查询到达时具有正确的结果,但是我的问题是如何知道该查询与其Laravel查询的等效项?

SELECT * FROM table1 AS a 
LEFT JOIN table1 AS b 
ON (a.column1 = b.column1 AND a.column2 < b.column2)
WHERE b.column2 is null;

And then I use this query in Laravel Query Builder which will query the wrong results. 然后,我在Laravel查询生成器中使用此查询,它将查询错误的结果。

DB::table('table1 As a')
->leftJoin('table1 As b', 'a.column1', '=', 'b.column1')
->leftJoin('table2 As c','a.column2', '<', 'c.column2')
->whereNull('c.column2')
->get();

This Laravel query is equivalent to this MySQL query which will, unfortunately, query the same wrong results: 此Laravel查询等效于此MySQL查询,不幸的是,它将查询相同的错误结果:

SELECT * FROM table1 AS a 
LEFT JOIN table1 AS b 
ON (a.column1 = b.column1 AND )
LEFT JOIN table1 AS c
ON (a.column2 < c.column2)
WHERE b.column2 is null;

You need to pass a function to the leftJoin() Something like this... 您需要将一个函数传递给leftJoin()东西...

DB::table('table1 as a')
    ->leftJoin('table1 as b', function($join) {
        return $join->on('a.column1', '=', 'b.column1')
            ->whereColumn('a.column2', '<', 'b.column2');
    })->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM