我有一个包含所有产品详细信息的表名称 products 和另一个包含每个仓库的产品数量详细信息的 whs_products。
我想从产品表中选择 ID、代码和名称以及数量总和,其中 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");
我得到的是 whs_products 中存在的列表产品,而不是总和。有些产品被列出两次,因为它们在 whs_products 中有 2 个条目。
我只想在没有数量的地方列出所有产品一次,我想在数量中输入 0,而在 whs_products 中它大于 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_products 获取数量。对于某些产品,数量是 2 或 3 倍,具体取决于每个仓库。
对此的任何解决方案。 非常感谢您的支持。
最佳答案
请尝试以下查询和评论。
示例数据:-
产品
PID PNAME
1 j
2 k
3 m
whs_Products
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 中
这里有一个先机供您尝试。起初我的印象是您已经知道 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;
}
}
按 OP 要求在评论中编辑 LEFT JOIN
要在 Products 表中显示所有产品,请执行以下操作:
在
select
中显示Products
表中的pid
。使用
来自 Products Left 加入 Whs_Products
Group by pid
来自Products
表
关于php - 使用 codeigniter 中的连接事件记录获取数据库字段的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14039120/