【问题标题】:using mysql join to show not match value使用 mysql join 显示不匹配值
【发布时间】:2016-09-22 04:14:50
【问题描述】:

我有一个查询要加入 3 个表。

$this->db->select("a.user_id as id, a.plate_number as plate_number, a.current_lat as lat, a.current_lon as lon, a.created_on as created_on, a.updated_on as updated_on, a.available as available, a.location_id as location_id, b.user_name as name, b.user_email as email, b.user_phone as phone, c.name as location_name");
        $this->db->from('user_driver as a');
        $this->db->join('user as b', 'a.user_id = b.user_id');
        $this->db->join('vendor_location as c', 'a.location_id = c.location_id');
        $query = $this->db->get();
        $data['driver'] = $query->result_array();

user_driver表结构:

vendor_location 表结构:

结果:

我想显示user_driver 表的其余部分,即使没有与vendor_location 表匹配的值。 LocationName 字段可以填充 NULL 而不是根本不显示任何内容。

我尝试了left outerfull outer,但它不起作用。它给我留下了唯一的一行显示。

【问题讨论】:

  • vendor_location 表中哪个是外键?
  • 这样接近:...user_driver INNER JOIN user ON .... LEFT JOIN vendor_location ON. ..
  • location_id@AT-2016
  • 请用真实数据替换截图(复制粘贴)

标签: mysql database codeigniter join


【解决方案1】:

即使没有与 vendor_location 表匹配的值,我也想显示 user_driver 表的其余部分。

为此,您应该使用LEFT JOIN。它允许您从左侧表中获取行,即使右侧表中没有匹配项。

$this->db->select("a.user_id as id, a.plate_number as plate_number, a.current_lat as lat, a.current_lon as lon, a.created_on as created_on, a.updated_on as updated_on, a.available as available, a.location_id as location_id, b.user_name as name, b.user_email as email, b.user_phone as phone, c.name as location_name");
$this->db->from('user_driver as a');
$this->db->join('user as b', 'a.user_id = b.user_id');
$this->db->join('vendor_location as c', 'a.location_id = c.location_id', 'left');//modify this line
$query = $this->db->get();
$data['driver'] = $query->result_array();

【讨论】:

  • 我只需要在两个join 查询中添加left。谢谢顺便说一句:)
【解决方案2】:

你试过这样吗

$this->db->join('user as b', 'a.user_id = b.user_id', 'LEFT');
    $this->db->join('vendor_location as c', 'a.location_id = c.location_id', 'LEFT');

【讨论】:

  • 谢谢,我应该在两个连接查询中添加left :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
相关资源
最近更新 更多