2017-07-03 83 views
3

我有兩個以上的表,同時從數據庫中取出2,00,000記錄需要太多時間我期待什麼,所以我需要將它轉換爲子查詢?在SQL(laravel控制器)中轉換聯接到子查詢

下面的代碼:

->join('track_details','track_details.code','=',$esealTable.'.primary_id') 
->join('track_history as th','th.track_id','=','track_details.track_id') 
->join('locations as l','l.location_id','=','th.src_loc_id') 
->join('products','products.product_id','=',$esealTable.'.pid') 
->where(['level_id'=>0, 'products.product_type_id'=>8003]) 
->whereIn('l.location_type_id',[741,744]) 
->whereIn('th.transition_id',[537,569]); 
->get(['primary_id as iot','products.material_code','th.sync_time as datetime']) 
->take(200000); 
+0

我認爲當您從查詢中獲取數據時,2,00,000不會太多。但是,使用自定義方法和循環處理數據時需要時間。 –

+0

是啊謝謝@Sagar Gautam其實我有array_map()和array_unique方法,同時檢索到JSON這個數據。 –

+0

所以,你必須尋找更好的方式來檢索數據,而不是查詢優化 –

回答

1

如果你需要所有這些在jsonquery檢索data

Laravel提供了類似於toArray()功能toJson()功能。請參閱文檔here。你只需要在查詢像這樣的末尾添加toJson()

->join('track_details','track_details.code','=',$esealTable.'.primary_id') 
... 
... 
.. 
->get(['primary_id as iot','products.material_code','th.sync_time as datetime']) 
->take(200000) 
->toJson(); 

通過這種方式,您可以直接獲取的數據轉換爲json格式。