左联接,并使用LARAVEL 6.5.0仅返回右表中的最新记录

时间:2020-02-06 02:56:21

标签: php sql laravel join left-join

{=IF(A2:A11=F2,A2:D11,"")}

我想每个nameID仅返回最新的记录,并且仅返回一个记录 右表,我不知道要使用什么代码

这是我要返回的结果

const [first, second] = require("./callee.js");

first("bob");

Controller.php

Table 1
----------
NameID     Name
------------------
1           A
2           B
3           C
-----------------

Table 2
--------------------
ID   NameID   Order   
--------------------
1      1      Sugar
2      1      Salt 
3      2      Garlic 
4      2      Sugar
5      2      Onion
6      3      Oil
7      3      Black pepper 

3 个答案:

答案 0 :(得分:0)

使用不存在的过滤器

select Name, Order

from Table1 a 
inner join
(
Select a.NameID, Order from Table2 a 
where not exists(select 1 from Table2 b where a.NameID  = b.NameID  and a.ID < b.ID)
)b on a.NameID = b.NameID

答案 1 :(得分:0)

尝试

$data = Table1::select('Table1.Name', 'Table2.Order','Table2.ID')
->leftJoin('Table2', function($query) {
   $query->on('Table1.NameID','=','Table2.NameID')
        ->whereRaw('Table2.ID IN (select MAX(a2.ID) from Table2 as a2 join Table1 as u2 on u2.NameID = a2.NameID group by u2.NameID)');
})->get();

已编辑:

$data = Table1::select('Table1.Name', 'Table2.Order','Table2.ID')

答案 2 :(得分:0)

您可以在脚本下方尝试此操作-

SELECT B.NameID, B.Name, C.[Order]
FROM 
(
    SELECT Nameid,MAX(ID) ID
    FROM table_2
    GROUP BY NameID
)A
INNER JOIN Table_1 B ON A.NameID = B.NameID
INNER JOIN Table_2 C ON A.NameID = C.NameID AND A.ID = C.ID