Codeigniter加入多个条件

时间:2013-04-13 19:54:43

标签: mysql codeigniter join

我正在使用Codeigniter Active Records类,我希望将users表与我的clients表联系起来,以便我可以显示用户的“真实”名称,而不仅仅是他们的ID。

以下是clients表的示例(示例),列a_1,a_2和a_3对应于我的users表,具体而言,user id

  clients
|--------|---------|----------|-----------|----------|
|  id    |   name  |   a_1    |    a_2    |   a_3    |
|--------|---------|----------|-----------|----------|
|   1    |   Paul  |    2     |     4     |    1     |

我的users表看起来像这样:

   users
|--------|---------|----------|
|  id    |  first  |   last   |  
|--------|---------|----------|
|   1    |   Paul  |  Blake   |
|--------|---------|----------|
|   2    |   Dan   |   Doe    |
|--------|---------|----------|
|   3    |  Steve  |  Smith   |
|--------|---------|----------|
|   4    |  Harry  |  Jones   |
|--------|---------|----------|

所以,基本上,如果我从clients表中选择并加入它,它将如下所示:

  clients
|--------|---------|----------|-----------|----------|
|  id    |   name  |   a_1    |    a_2    |   a_3    |
|--------|---------|----------|-----------|----------|
|   1    |   Paul  | Dane Doe |Harry Jones|Paul Blake|

到目前为止,我已经尝试过(它没有用,它只为所有人显示相同的名称):

<?
 $this->db
  ->select('name, a_1, a_2, a_3')
  ->from('clients')
  ->join('users', 'users.id=a_1 OR users.id=a_2 OR users.id=a_3');

任何帮助都会很棒!

解决方案:

以下是我能想出的作品(感谢@elavarasan lee):

<?
 $this->db
  ->select('CONCAT(u1.first," ", u1.last) as a_1_name, CONCAT(u2.first," ", u2.last) as a_2_name, CONCAT(u3.first," ",u3.last) as a_3_name', FALSE)
  ->from('clients')
  ->join('users AS u1', 'u1.id=a_1', 'left')
  ->join('users AS u2', 'u2.id=a_2', 'left')
  ->join('users AS u3', 'u3.id=a_3', 'left');

3 个答案:

答案 0 :(得分:25)

试试这个

$this->db
  ->select('*')
  ->from('clients')
  ->join('users', 'users.id = clients.a_1 OR users.id=clients.a_2 OR users.id = clients.a_3');

$query = $this->db->get();

return $query->result();

答案 1 :(得分:8)

@Dodinas:我在MYSQL查询方面得到了解决方案。我发现很难将查询转换为CI Active Record。但试试这个:


    $sql = "SELECT `name`, CONCAT(`u1`.`first`,' ', `u1`.`last`) as a_1, 
                           CONCAT(`u2`.`first`,' ', `u2`.`last`) as a_2, 
                           CONCAT(`u3`.`first`,' ', `u3`.`last`) as a_3 
            FROM `clients` 
            LEFT JOIN `users` as `u1` ON (`u1`.`id`=`a_1`)
            LEFT JOIN `users` as `u2` ON (`u2`.`id`=`a_2`)
            LEFT JOIN `users` as `u3` ON (`u3`.`id`=`a_3`)";

    $result = $this->db->query($sql);


screenshot of the query result taken from PHP Myadmin

答案 2 :(得分:0)

$ this-> db-> where('b_cdatetime BETWEEN“'。date('Ym-d',strtotime($ this-> input-> post('from_date')))。'”和“'。 date('Ym-d',strtotime($ this-> input-> post('to_date')))。'“');                 $ this-> db-> where('tb_bill_history.b_status =',$ this-> input-> post('status'));                 $ this-> db-> select('*');
                $ this-> db-> from($ table);                 $ this-> db-> join('tb_bill_history','tb_bill_history.bill_no = mst_bills.b_bill_no AND tb_bill_history.b_exec_id = mst_executive.e_id');