2013-08-19 20 views
0

我有一個查詢如下。MySQL限制未設置到特定範圍

$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(); 

我想拉回一條記錄,因此「限制(1)」,但它拉回多條記錄。代碼對我來說看起來很完美。任何幫助將不勝感激。

乾杯。

相關的子查詢會起作用嗎?!

回答

0

我們需要查看不同表格之間的關係才能得到確切的原因,但我的猜測是您在這些表格之間存在一對多關係,並且需要GROUP BY來總結它們。

我建議使用WHERE子句運行您的查詢,該子句將主行限制爲一個結果(例如devices.id = x)。然後,您將看到爲該ID返回多行,使用像GROUP BY這樣的聚合函數將這些結果合併到一行中。