使用join codeigniter显示不在其他表中的数据

问题描述 投票:0回答:1

我有2个表,我尝试加入将2个表与codeigniter结合起来,但是当我创建查询连接时,由于数据不在另一个表中而没有出现数据,我该怎样才能解决这个问题?

tbl_fruit
_______________
| id |  fruit | 
|----|--------|
| 0  | manggo | 
| 1  | apple  | 
| 2  | banana | 
| 3  | orange | 
| 4  | avocado| 

tbl_proc
_______________
| id |  proc  | 
|----|--------|
| 0  | juice  | 
| 1  | blend  | 
| 2  | shake  | 

tbl_master
____________________________________
| id | id_fruit | id_proc | client  |
|----|----------|---------|---------|
|  0 |     2    |         |         | //How display on join
|  1 |     1    |    2    | nana    |
|  2 |     3    |    2    | george  |
|  3 |     4    |    0    | smith   |
|  4 |     0    |         | billy   | //How display on join
|  5 |     2    |    1    | Jack    |

tbl_result
----------------------------------------
| no | name fruit | name proc | client |
|----|------------|-----------|--------|
|  0 |  apple     | shake     | nana   |
|  1 |  orange    | shake     | george |
|  2 |  avocado   | juice     | smith  |
|  3 |  banana    | blend     | smith  |    

    $query = $this->db->select('*')
                      ->from('tb_result')
                      ->join('tb_fruit', 'tb_fruit.id = tb_result.id_fruit')
                      ->join('tb_proc', 'tb_proc.id = tb_result.id_proc')
                      ->get();
    return $query->result(); 

如何在tbl_master上显示数据,该数据在其他表中没有数据但出现在连接的表中?

php mysql codeigniter codeigniter-3
1个回答
1
投票

在连接函数的第三个参数中使用LEFT JOIN

$query = $this->db->select('*')
                      ->from('tbl_master')
                      ->join('tbl_fruit', 'tbl_fruit.id = tbl_master.id_fruit', 'left')
                      ->join('tbl_proc', 'tbl_proc.id = tbl_master.id_proc', 'left')
                      ->get();
    return $query->result(); 

它应该导致这个SQLFIDDLE

© www.soinside.com 2019 - 2024. All rights reserved.