如何在查询CI语法中编写SQL查询?

时间:2014-04-07 09:42:02

标签: php mysql codeigniter

我有以下查询,我需要在Codeignitor模型中编写

SELECT DISTINCT make FROM equipment_nonconnected_master WHERE Equipment_NonConnected_Type_Master_ID IN (select Equipment_NonConnected_Type_Master_ID FROM equipment_nonconnected_type_master)

我只知道简单地用Codeignitor编写的select查询,如下所示:

示例:

$this->db->distinct();
$this->db->select('make');
$this->db->order_by('make', 'asc');
$query = $this->db->get('carriermodels');

有人可以帮我用CI语法编写查询

1 个答案:

答案 0 :(得分:3)

您可以使用简单的where()功能

来完成此操作
$subquery="SELECT 
    Equipment_NonConnected_Type_Master_ID 
  FROM
    equipment_nonconnected_type_master";
$this->db->distinct();
$this->db->select('make');
$this->db->from('carriermodels');
$this->db->where('Equipment_NonConnected_Type_Master_ID IN('.$subquery.')');
$this->db->order_by('make', 'asc');
$query = $this->db->get();

或者更好地使用join

$this->db->distinct();
$this->db->select('c.make');
$this->db->from('carriermodels c');
$this->db->join('equipment_nonconnected_type_master m','c.Equipment_NonConnected_Type_Master_ID =m.Equipment_NonConnected_Type_Master_ID ');
$this->db->order_by('c.make', 'asc');
$query = $this->db->get();