2016-08-12 115 views
0

我嘗試將查詢轉換爲mysql到laravel查詢生成器,但它不工作。我在SQL查詢的東西像這樣:Laravel查詢生成器加入多個子查詢

SELECT * 
FROM claim.t_meter a 
JOIN 
    (
    SELECT MAX(REPLACEMENT_COUNT) AS MAX_REPLACEMENT_COUNT, meter_no 
    FROM claim.t_meter 
    WHERE bukken_uid = 1. AND deleted = 0 
    GROUP BY meter_no 
) b ON a.meter_no = b.meter_no AND a.REPLACEMENT_COUNT = b.MAX_REPLACEMENT_COUNT 
LEFT JOIN 
    (
    SELECT NAME, meter_no, INSPECTION_GROUP_UID 
    FROM claim.m_inspection_group c 
    JOIN claim.t_inspection_group_setting d ON c.uid = d.inspection_group_uid 
) e ON a.meter_no = e.meter_no 
GROUP BY a.meter_no 
ORDER BY inspection_group_uid ASC 

現在,我使用:

$query = ' SELECT * FROM t_meter a JOIN ('; 
$query .= ' SELECT MAX(REPLACEMENT_COUNT) AS MAX_REPLACEMENT_COUNT, meter_no'; 
$query .= ' FROM t_meter WHERE bukken_uid = '.$id.' AND deleted = 0 GROUP BY meter_no)'; 
$query .= ' b ON a.meter_no = b.meter_no AND a.REPLACEMENT_COUNT = b.MAX_REPLACEMENT_COUNT'; 
$query .= ' LEFT JOIN (SELECT NAME,meter_no,INSPECTION_GROUP_UID FROM m_inspection_group c'; 
$query .= ' JOIN t_inspection_group_setting d ON c.uid = d.inspection_group_uid'; 
$query .= ') e ON a.meter_no = e.meter_no GROUP BY a.meter_no ORDER BY inspection_group_uid ASC'; 
$arrInFo = DB::select($query); 

這不是最好的辦法,請大家幫忙!

回答

0

我的解決辦法是:

$arrInFo = TMeter::SELECT(
        't_meter.*', 
        'ORDER_BY_TERMINAL' 
       ) 
      ->join(DB::raw('(SELECT MAX(REPLACEMENT_COUNT) AS MAX_REPLACEMENT_COUNT, METER_NO FROM `t_meter` WHERE BUKKEN_UID = '.$bukken_uid.' AND DELETED = '.Constants::IS_NOT_DEL.' GROUP BY METER_NO) b'), function($join) 
      { 
       $join->on('t_meter.METER_NO', '=', 'b.METER_NO') 
        ->on('t_meter.REPLACEMENT_COUNT', '=', 'b.MAX_REPLACEMENT_COUNT'); 
      }) 
      ->leftJoin(DB::raw('(SELECT NAME, METER_NO, ORDER_BY_TERMINAL, INSPECTION_GROUP_UID, d.UID as setting_uid FROM `m_inspection_group` c JOIN t_inspection_group_setting d on c.UID = d.INSPECTION_GROUP_UID AND c.UID = '.$id.') e'), function($join) { 
       $join->on('t_meter.METER_NO', '=', 'e.METER_NO'); 
      }) 
      ->groupBy('METER_NO') 
      ->get();