简体   繁体   中英

convert mysql query in codeigniter query

Convert mysql query into codeigniter query

Current Query :


$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);

In Bold query I want to append search variable like

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

Any help and ideas will be appreciated.

Unfortunately I don't think it's possible to use codeigniters active record class to append a where clause to your existing SQL. The active record class can only handle simple joins between tables.

To append it to your existing query you could use query binding to pass the variable to the query.

$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));

Try this one

$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

OR see CodeIgniter Subqueries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM