在codeigniter查询中转换mysql查询

时间:2013-09-30 06:16:08

标签: php mysql sql codeigniter

将mysql查询转换为codeigniter查询

当前查询:


$query = "SELECT a.*, b.cost AS future_cost, b.start_date AS future_date
          FROM (
            SELECT * FROM (
              SELECT * FROM outbound_routes 
              ORDER BY start_date
            ) x 
          GROUP BY pattern
          ) a
          LEFT JOIN (
            SELECT * FROM outbound_routes 
            ORDER BY start_date
          ) b 
          ON a.pattern = b.pattern AND a.id != b.id
          GROUP BY a.pattern";

$result=$this->db->query($query);

在粗体查询中,我想附加搜索变量,如

 $this->db->where('pattern','1');

任何帮助和想法都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

不幸的是,我认为不可能使用codeigniters active record class将where子句附加到现有的SQL中。活动记录类只能处理表之间的简单连接。

要将其附加到现有查询,您可以使用查询绑定将变量传递给查询。

$query = "SELECT a.*, b.cost AS future_cost, b.start_date AS future_date
          FROM (
            SELECT * FROM (
              SELECT * FROM outbound_routes 
              ORDER BY start_date
            ) x 
          GROUP BY pattern
          ) a
          LEFT JOIN (
            SELECT * FROM outbound_routes 
            ORDER BY start_date
          ) b 
          ON a.pattern = b.pattern AND a.id != b.id
          GROUP BY a.pattern
          WHERE pattern = ?";

$result = $this->db->query($query, array(1));

答案 1 :(得分:0)

试试这个

$this->db->select('select a.*, b.cost AS future_cost, b.start_date AS future_date');
$this->db->from('(select * from   (select * from outbound_routes order by start_date) x group by pattern) a');
$this->db->join('(select * from outbound_routes order by start_date) b', 'a.pattern = b.pattern and a.id != b.id','left ');
$this->db->where('a.pattern','1');
$this->db->group_by("a.pattern"); 
$result=$query = $this->db->get();

Active Record

或参见CodeIgniter Subqueries