0

我有一个查询如下。

$tests = DB::select('devices.id')
 ->select(array('devices.description', 'dev_desc'))
 ->select(array('device_types.description', 'devtype_init'))
 ->select(array('actions.description', 'test_desc'))
 ->select(array('history.dt_logged', 'last_test'))
 ->select(array(DB::expr('history.dt_logged + (devices.frequency * 7 * 24 * 60 * 60)'), 'next_test'))
 ->from('history')
 ->join('actions')->on('history.action_id', '=', 'actions.id')
 ->join('devices')->on('history.device_id', '=', 'devices.id')
 ->join('device_types')->on('devices.device_type_id', '=', 'cal_device_types.id')
 ->and_where(DB::expr('history.dt_logged + (devices.frequency * 7 * 24 * 60 * 60)'), '>=', $start)
 ->and_where(DB::expr('history.dt_logged + (devices.frequency * 7 * 24 * 60 * 60)'), '<=', $end)
 ->where('device_types.description', '=', 'Calibration')
 ->order_by('history.dt_logged', 'desc')->limit(1)
 ->execute();

我想拉回一条记录,因此是“limit(1)”,但它拉回了多条记录。代码对我来说看起来很完美。任何帮助将不胜感激。

干杯。

相关子查询会起作用吗?

4

1 回答 1

0

我们需要查看不同表之间的关系以获得确切的原因,但我的猜测是您在这些表之间存在一对多的关系,并且需要GROUP BY总结它们。

WHERE我建议使用将主行限制为一个结果的子句运行您的查询(例如,devices.id = x)。然后,您将看到针对该 ID 返回的多行,使用 GROUP BY 之类的聚合函数将这些结果组合成一行。

于 2013-08-19T15:40:44.900 回答