Laravel 4.2中的SubQueries

时间:2015-05-26 17:29:23

标签: mysql laravel-4 eloquent

任何人都可以教我如何在Laravel 4.2中使用这样的查询

SELECT 
    t.Truck_Number, 
    t.Created_dt,
    t.Latitude,
    t.Longitude,
    t.Speed,
    t.Heading 
FROM 
    truckgps t 
INNER JOIN 
    ( 
        SELECT 
            Truck_Number,
            max(Created_dt) as MaxDate 
        FROM
            truckgps 
        GROUP BY
            Truck_Number
    ) tm 
ON
    t.Truck_Number = tm.Truck_Number AND
    t.Created_dt = tm.MaxDate

此查询由其他人提供,使用laravel可以更好吗?

2 个答案:

答案 0 :(得分:1)

使用“Laravel查询”构建器 - 您可以这样做:

   $results = DB::select("SELECT 
                         t.Truck_Number, 
                         t.Created_dt, 
                         t.Latitude, 
                         t.Longitude, 
                         t.Speed,
                         t.Heading FROM truckgps t 
        INNER JOIN 
        ( SELECT Truck_Number, max(Created_dt) as MaxDate from truckgps group by Truck_Number )   
           tm on t.Truck_Number = tm.Truck_Number and t.Created_dt = tm.MaxDate");

或者如果你有参数,你可以像这样绑定:

DB::select("select count(1) count from table t where t.id= ? and t.roles_id = ?", 
            array($id, $role_id)
          );

答案 1 :(得分:-1)

如果你有两张桌子......我有一个解决你的问题的方法..你不需要使用连接。表1名称' truckgps'和表2名称' truckgpss'我的答案

$truckgps = DB::table('truckgps')->select('Truck_Number','Created','Latitude','Longitude','Speed','Heading ')->get();

foreach ($truckgps as $t)
{

$result = DB::table('truckgpss')->select('MAX(Created_dt) AS MaxDate ','Truck_Number')->where('MaxDate','=',$t->Created_dt )->where('Truck_Number','=',$t->Truck_Number)->groupBy('Truck_Number')
                 ->get();


// if u need value convert array to string use another foreach loop here

foreach ($result as $value)
{

echo $value->Truck_Number; // now u can see the  result truck no..


   }


}

我觉得它对你有所帮助......谢谢..