2015-05-26 108 views
0

誰能教教我怎麼才能在Laravel 4.2子查詢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變得更好?

回答

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名 '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.. 


    } 


} 

我認爲它的幫助下到u ...謝謝你..