【问题标题】:How to join two table for search on base of primary and foreign key?如何根据主键和外键连接两个表进行搜索?
【发布时间】:2015-08-24 10:16:00
【问题描述】:

我有两张桌子,一张是table1

id名称价格

1 个名字 1 100

2 名称2 200

table2

id authorityId 机构 start_date end_date

1 1 个机构1 1-2-2015 2-12015

我想在第二个表中搜索对我来说很好的值 但我想根据外键(table1_id)从第一个表中获得名称。我该怎么做。任何帮助将不胜感激?

这是我的代码

控制器:

public function searchResult()
{

    $search_term = array(
    'authorityId' => $this->input->get('authority'),
    'grantVillage' => $this->input->get('village'),
    'startDate' => $this->input->get('startDate'),
    'endDate' => $this->input->get('endDate'));
    //print_r($search_term);
    $data['searchResult'] = $this->grant_model->searchResult($search_term);
    $this->load->view('searchResult',$data);

}

型号:

 public function searchResult($search_term)
    {
           $this->db->select('*');
           $this->db->from('grant_data');
           $this->db->like('authorityId', $search_term['authorityId']);
           $this->db->like('grantVillage', $search_term['grantVillage']);
           $this->db->like('startDate', $search_term['startDate']);
           $this->db->like('certificate', $search_term['certificate']);
           $this->db->like('endDate', $search_term['endDate']);
           $query = $this->db->get();
           return $query->result();
    }

【问题讨论】:

    标签: php ajax codeigniter


    【解决方案1】:

    请这样使用--

       $this -> db -> select('*');
       $this -> db -> from('table2');
       $this->db->join('table1','table1.table1_id = table2.autority_id');
       $this -> db -> where('table2'.'id', 5);
       $query = $this -> db -> get();
       return $query->result_array();
    

    它会得到两个表数据试试...

    【讨论】:

    • 感谢您的回复。如果用户在搜索字段中选择autority_id(名称),这将正常工作。如果用户不会选择autority_id,那么我该怎么做。因为我有四个字段在搜索中。
    【解决方案2】:
    public function searchResult($search_term)
        {
               $this->db->select('*');
               $this->db->from('grant_data');
               $this->db->like('authorityId', $search_term['authorityId']);
               $this->db->like('grantVillage', $search_term['grantVillage']);
               $this->db->like('startDate', $search_term['startDate']);
               $this->db->like('certificate', $search_term['certificate']);
               $this->db->like('endDate', $search_term['endDate']);
               $query = $this->db->get();
               return $query->result();
        }
    

    运行这个查询结果是

    id foreign_key field1 field2 field3

    现在我想根据foreign_key从另一个表中取名字

    我该怎么做?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多