简体   繁体   English

从MySql中全选并加入其他

[英]Select all from MySql and join other

I have this codeigniter function 我有这个codeigniter函数

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;

}

It selects all data from table clients. 它从表客户端选择所有数据。 One of them is "client_team_profile_id" - the owner of this client. 其中之一是“ client_team_profile_id”-该客户端的所有者。

I also need to join other table - team profiles. 我还需要加入其他表格-团队资料。 There we can find team_profile_id (there are ids of users in system) and team_profile_full_name - names of users. 在这里我们可以找到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                    |

I need to select all data from table CLIENTS (as we can see - Select *) and also get name of team user connected to client and set a parameter for result - AS f.ex. 我需要从表CLIENTS中选择所有数据(如我们所见-选择*),还需要获取连接到客户端的团队用户的名称,并为结果设置参数-ASf.ex。 client_owner_name. client_owner_name。

I appreciate your help. 我感谢您的帮助。

So you can add this JOIN to your existing query 因此,您可以将此JOIN添加到现有查询中

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"

You may also need to change this bit of code to use the table alias like so 您可能还需要更改这段代码以使用表别名,如下所示

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

And also 并且

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM