2015-12-13 39 views
1

我這個笨功能選擇所有從MySQL,並加入其他

function allClients($orderby = 'clients_company_name', $sort = 'ASC') 
{ 

    //profiling:: 
    $this->debug_methods_trail[] = __function__; 

    //declare 
    $conditional_sql = ''; 

    //check if any specifi ordering was passed 
    if (! $this->db->field_exists($orderby, 'clients')) { 
     $orderby = 'clients_company_name'; 
    } 

    //check if sorting type was passed 
    $sort = ($sort == 'asc' || $sort == 'desc') ? $sort : 'ASC'; 

    //----------sql & benchmarking start---------- 
    $this->benchmark->mark('code_start'); 

    //_____SQL QUERY_______ 
    $query = $this->db->query("SELECT * 
             FROM clients 
             ORDER BY $orderby $sort"); 

    $results = $query->result_array(); //multi row array 

    //benchmark/debug 
    $this->benchmark->mark('code_end'); 
    $execution_time = $this->benchmark->elapsed_time('code_start', 'code_end'); 

    //debugging data 
    $this->__debugging(__line__, __function__, $execution_time, __class__, $results); 
    //----------sql & benchmarking end---------- 

    //return results 
    return $results; 

} 

它選擇從表客戶的所有數據。其中之一是「client_team_profile_id」 - 該客戶的所有者。

我還需要加入其他表 - 團隊配置文件。在那裏,我們可以找到team_profile_id(系統中有用戶的id)和team_profile_full_name - 用戶的名稱。

Table: clients 

clients_id|clients-company_name|client_address|clients_team_profile_id 
1   |Apple    |some street |2 
2   |Dell    |some street |5 


Table team_profile 

team_profile_id | team_profile_full_name| 
2    |John     | 
5    |Bob     | 

我需要從表中客戶端的所有數據(我們可以看到 - 選擇*),並獲得團隊的用戶連接到客戶端的名稱,併爲結果的參數 - AS f.ex. client_owner_name。

我感謝您的幫助。

+0

那麼,如果_製作一個JOIN它不是一個很大的問題_並且由於您的查詢是純文本的,只需將JOIN添加到您現有的查詢 – RiggsFolly

+0

不幸的是我不能這樣做,你能給予有用的幫助嗎? –

+0

除非您顯示要從中查詢數據的所有表的實際表定義。你的描述不清楚,而且這隻會導致我的猜測,然後你說這是行不通的,我們一起轉轉 – RiggsFolly

回答

0

所以,你可以添加這個連接到現有查詢

SELECT c.*, t.team_profile_full_name as client_owner_name 
FROM clients c 
    JOIN team_profile t ON t.team_profile_id = c.clients_team_profile_id 
ORDER BY $orderby $sort" 

您可能還需要修改這段代碼使用表的別名,像這樣

//check if any specifi ordering was passed 
if (! $this->db->field_exists($orderby, 'clients')) { 
    $orderby = 'c.clients_company_name'; 
} 

而且還

function allClients($orderby = 'c.clients_company_name', $sort = 'ASC') 
相關問題