如何联接2个表并返回值

时间:2019-04-24 06:18:53

标签: php codeigniter

我有2张桌子

第一张桌子:

id | order_number | product_id
1  | 111111       | 121
2  | 222222       | 343
3  | 333333       | 344

第二张桌子

id | order_number | paid
3  | 111111       | 1
6  | 222222       | 1

我可以获取第二个表不拥有的第一个表中的所有数据吗?

示例

order_number 333333不属于第二个表。

使用框架Codeigniter 3的上述情况的代码如何?

我尝试了下面的代码,但在2表返回相同的值

$query = $this->db->select('*') 
         ->from('first_tbl') 
         ->join('second_tbl', 'second_tbl.order_number = first_tbl.order_number', 'right') 
         ->get();
var_dump($query->result_array()); 

对不起,英语不好

2 个答案:

答案 0 :(得分:0)

您可以使用此查询

 SELECT t1.* FROM first_tbl AS t1
 LEFT JOIN second_tbl AS t2 ON t1.order_number = t2.order_number
 WHERE t2.ID IS NULl

它将仅返回333333记录

例如,请参见此DB fiddle

这是在CI中的外观:

$this->db->select("t1.*")
$this->db->from("first_tbl AS t1");
$this->db->join("second_tbl AS t2 ", "t1.order_number = t2.order_number", "left");
$this->db->where("t2.id IS NULL");

var_dum($this->db->get()->result());

答案 1 :(得分:0)

    $this->db->SELECT('table1.order_number,table1.product_id,table2.paid');
    $this->db->FROM('table1');
    $this->db->JOIN('table2', 'table2.order_number = table1.order_number', 'LEFT');
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return false;
    }