我是codeigniter的新手,我想请一些帮助。如何将此mysql查询转换为codeigniter活动记录。 这是我的查询
SELECT p.*, s.product_id,sum(s.quantity) as st, sumq,
sum(s.quantity) - sumq as a, concat (prod_desc,' ',brand_name) as names
from stocks s join ( select product_id, sum(quantity) sumq
from order_details group by product_id) o on s.product_id = o.product_id join (select * from products) p on p.prod_id = s.product_id
join (select * from brand) b on b.brand_id = p.brand_id
group by product_id having a >= 1
答案 0 :(得分:0)
$this->db->select('product_id, sum(quantity) sumq')
->from('order_details')
->group_by('product_id');
$query_2 = $this->db->get_compiled_select();
$this->db->from('products');
$query_3 = $this->db->get_compiled_select();
$this->db->from('brand');
$query_4 = $this->db->get_compiled_select();
$final_query = "SELECT p.*, s.product_id,sum(s.quantity) as st, sumq,
sum(s.quantity) - sumq as a, concat (prod_desc,' ',brand_name) as names from stock s JOIN ($query_2) o on s.product_id = o.product_id JOIN ($query_3)p on p.prod_id = s.product_id JOIN ($query_4)b on b.brand_id = p.brand_id
GROUP BY product_id having a >= ?";
$a = 1;
$this->db->query($final_query,array($a));
echo $this->db->last_query();
Codeigniter无法在其活动记录中使用子查询,因此我使用$this->db->get_compiled_select();
生成来自活动记录的已编译select语句,然后在$final_query
中编写新查询并使用预准备语句运行它。
Does codeigniter $this->db->query() or $this->db->escape() prevent SQL Injection?
答案 1 :(得分:0)
我得到了答案。我只是在join中输入select语句。
$this->db->select("p.*,c.category_name,s.size,b.brand_name,sum(t.quantity) as total_q,sumq,sum(t.quantity)-sumq as aq, CONCAT(b.brand_name,' ',p.prod_desc,' ',s.size) AS name", FALSE)
->from('stocks t');
$this->db->join('products p','p.prod_id = t.product_id','full')
->join('category c','p.category_id = c.category_id','full');
$this->db->join('sizes s','p.size_id = s.size_id','full');
$this->db->join('brand b','p.brand_id = b.brand_id','full');
$this->db->join('(select product_id, sum(order_quantity) sumq from order_details group by product_id) as o','t.product_id = o.product_id','full');
$this->db->group_by('prod_id')
->order_by('name');
$result=$this->db->get();
if($result->num_rows()>0){
foreach ($result->result() as $data) {
$hasil[] = $data;
}
return $hasil;
}