2013-01-04 34 views
0

我正在使用codeigniter。我想要一個where子句來獲得totalQuantity小於alterQuantity的產品。我在select子句中使用sum來獲得totalQuantity。其中SUM(table1.field)> =聯接表中的table2.field

$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity") 
->from('products') 
->where('alertQuantity <=', 'totalQuantity') 
->join('whs_products', 'whs_products.product_id=products.id', 'left') 
->group_by("products.id"); 
$this->db->get(); 

我不知道,如果試圖如何獲得所需的產品:( 編輯 這

->where('alertQuantity <=', 'totalQuantity') 

我得到的所有產品,但與 - >在哪裏( 'alertQuantity < =',' totalQuantity')沒有產品。

+0

我想你想使用'HAVING',不'WHERE'。 –

回答

0

就在你的SELECT語句添加FALSE,並嘗試

$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity",FALSE) 

$ this-> db-> select()接受可選的第二個參數。如果您將 設置爲FALSE,則CodeIgniter將不會嘗試使用反引號來保護您的字段或表 名稱。如果您需要複合選擇 聲明,這很有用。

從文件here

+0

謝謝LearneR。我已經嘗試了這一點,我已經得到所有的產品:(在這裏留下加入好嗎?我不知道加入 – Saleem

+0

放在加入後的條件 –

+0

累了,但同樣,如果試過這 - > where('alertQuantity < ','totalQuantity') 我得到的所有產品,但與 - > where('alertQuantity <=','totalQuantity')沒有產品。 – Saleem

0

試試這個:

SELECT p.id AS productid, p.code, p.name, p.unit, p.cost, p.price, wp.quantity AS totalQuantity, p.alert_quantity AS alertQuantity 
FROM products p 
LEFT JOIN (SELECT product_id, SUM(quantity) quantity 
       FROM whs_products GROUP BY product_id) wp ON wp.product_id = p.id AND p.alert_quantity <= quantity ; 
0

試試這個

$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity") 
->from('products') 
->join('whs_products', 'whs_products.product_id=products.id', 'left') 
->where('alertQuantity <= totalQuantity') 
->group_by("products.id"); 
$this->db->get(); 

echo $this->db->last_query();exit; //to check the query generated is correct or not 
相關問題