我已经尝试将mysql中的查询转换为laravel查询构建器,但它无法正常工作。我在sql中的查询是这样的:
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 :(得分: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();