我有一个表名products,其中包含所有产品详细信息,还有一个whs_products,其中包含每个仓库的产品数量详细信息。
我要从products表中选择id、code和name,以及products.id=whs_products.product_id的数量和
我在试这个
$this->db->select("id, code, name");
$this->db->from("products");
$this->db->join('whs_products', 'products.id = whs_products.product_id');
$this->db->select("quantity");
我得到的是WHSL产品中的产品,而不是总和。有些产品在whs_products中有两个条目,因此会被列出两次。
我想只列出一次所有的产品,如果没有数量,我想输入0,如果超过1,我想显示所有数量的总和
非常感谢您的帮助!
表结构
Products
id, code, name, unit, price
whs_products
id, product_id, warehouse_id, quantity
我还有仓库用的whs桌
身份、姓名、地址
我试过了,先生,
$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as 'totalQuantity'")
->from('products')
->join('whs_products', 'whs_products.product_id=products.id', 'left')
->group_by("products.id");
$this->db->get();
一切都很好。但产品总数计算错误。我认为系统在总产品中加1,每次都从whsúu产品中获得数量。对于某些产品,根据每个仓库的不同,数量是2或3次。
任何解决办法。我非常感谢你的支持。
最佳答案
请尝试以下查询和注释。
SQLFIDDLE DEMO
样本数据:-
产品
PID PNAME
1 j
2 k
3 m
世界卫生组织产品
WID PID QUANTITY
11 2 300
11 2 200
14 2 500
11 1 300
15 3 100
14 3 800
查询以在
whs_products
中按pid获取总计select pid, wid, sum(quantity)
from whs_products
group by pid, wid
;
结果:
PID WID SUM(QUANTITY)
1 11 300
2 11 500
2 14 500
3 14 800
3 15 100
使用变量获取
pid
的用户输入并通过pid、wid进行查询-- group by pid and wid
set @var:='2'
;
select a.pid, b.pname, a.wid, sum(a.quantity)
from whs_products a
join products b
on b.pid = a.pid
where a.pid = @var
group by a.pid, wid
;
结果:
PID PNAME WID SUM(A.QUANTITY)
2 k 11 500
2 k 14 500
仅按用户输入pid显示数量的最终查询
查询:
-- by pid only
set @var:='2'
;
select a.pid, b.pname, sum(a.quantity)
from whs_products a
join products b
on b.pid = a.pid
where a.pid = @var
group by a.pid
;
结果:
PID PNAME SUM(A.QUANTITY)
2 k 1000
因为OP想要编码器点火器
这是一个你可以试试的头巾。起初,我觉得您已经知道
codeigniter
的语法,您正在寻找SQL逻辑,因此可以将其转换为所需的格式。$this->db->select("a.pid, b.pname, count(a.quantity) as 'toalQuantity'");
$this->db->from('wsh_products a');
$this->db->join('products b', 'a.pid=b.pid', 'inner');
$this->db->group_by("a.pid");
$where = "a.pid = 2";
$this->db->get();
$query->results_array();
或者写一个函数:):
function getQuantity($prodid = false)
{
$this->db->select(a.pid, b.pname, count(a.quantity) as 'toalQuantity');
$this->db->join('wsh_products a', 'a.pid=b.pid');
if ($prodid !== false)
$this->db->where('a.pid', $prodid);
$query = $this->db->get('products b');
if($query->result() == TRUE)
{
foreach($query->result_array() as $row)
{
$result[] = $row;
}
return $result;
}
}
根据评论中
LEFT JOIN
的操作请求编辑SQLFIDDLE
要在产品表中显示所有产品,请执行以下操作:
在
select
表中显示pid
。使用
Products
from Products Left Join Whs_Products
来自Group by pid
表关于php - 在Codeigniter中使用连接事件记录获取db字段的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14039120/