如何在sql查询中连接两行表?

时间:2015-12-17 09:56:36

标签: mysql yii1.x

在我的employees表格中,我有三个字段first_namelast_namemiddle_name。我使用了csqldataprovider,如下所示。我想显示员工的全名。即,first_name + last_name + middle_name。所以我尝试了这个employees.concat(first_name,last_name,middle_name)它给了我一个错误,没有字段在员工中名为concat。

$sql    =   "SELECT employee_tasks.task_name as Task, employee_task_log.log as Log,
                            employees.first_name as Name, employee_task_log.id as Id
                    From employee_task_log 
                    Left join employee_tasks ON employee_tasks.id=employee_task_log.task_id 
                    Left join employees ON employees.id=employee_task_log.employee_id 
                    where employee_tasks.id ={$id} " ;

        $dataProvider   =   new CSqlDataProvider( $sql, array( 'keyField' => 'Id', 'pagination'=>false  ) );

如何连接name

1 个答案:

答案 0 :(得分:1)

使用 CONCAT_WS

CONCAT_WS(' ', first_name, middle_name, last_name);

所以查询将是:

SELECT employee_tasks.task_name as Task, employee_task_log.log as Log,
CONCAT_WS(' ', employees.first_name, employees.middle_name, employees.last_name) as Name,
employee_task_log.id as Id
From employee_task_log 
Left join employee_tasks ON employee_tasks.id=employee_task_log.task_id 
Left join employees ON employees.id=employee_task_log.employee_id 
where employee_tasks.id ={$id}