对codeigniter求和SQL中的1个以上的表


Sum more than 1 table from SQL on codeigniter

需要一些小帮助来解决这种情况。我看到codeigniter不支持UNION,我想找出这个方法来获得两个表的总和,具有相同的乘积id。

问题是,在sum 2表上,值是重复的或乘法的。

链接到SQL Fiddle

结构:

create table products
(id int, name varchar(9));
insert into products 
(id, name)
values
(1,'Product 1'),
(2,'Product 2'),
(3,'Product 3');

create table p_items
(puid int, prid int, quantity int);
insert into p_items
(puid, prid, quantity)
values
(11,1,100),
(11,2,100),
(11,2,100),
(14,2,100),
(14,3,100),
(15,3,100);
create table s_items
(puid int, prid int, quantity int);
insert into s_items
(puid, prid, quantity)
values
(11,1,1),
(11,2,1),
(11,2,1),
(13,2,1),
(15,3,1),
(13,3,1);

在正常SQL:中执行

select a.puid, b.name, a.prid, sum(a.quantity) as P_ITEMS, sum(c.quantity) as S_ITEMS
from p_items a
join products b
on b.id = a.prid
join s_items c
on c.prid = a.prid
group by a.prid;

代码点火器功能:

$this->alerts
            ->select('products.id as productid, products.name, sumt(p_items.quantity), sum(s_items.quantity)', FALSE)
            ->from('products')
            ->join('p_items', 'products.id = p_items.prid', 'left')
            ->join('s_items', 'products.id = s_items.prid')
            ->group_by("products.id");
            echo $this->alerts->generate();

非常感谢您的帮助。

您的问题是生成笛卡尔乘积,从而得到重复的和。以产品ID 3为例。您将其与p_items prid=3相关联。就其本身而言,这将给你200英镑的回报。然而,一旦您在s_items prid=3上加入,现在对于s_items中的每一行,它都必须与p_items中每一行相匹配。含义:

14 3 100 15 3 1
14 3 100 15 3 1
15 3 100 15 3 1
15 3 100 15 3 1
---------------
     400      4

除了产品表,哪张表是您的主表?如果使用p_items,则需要从s_items中获取第13行。同样,如果使用s_items,则不会从p_items获得第14行。

您可以使用子查询完成此操作:

select b.id, 
  b.name, 
  P_ITEMS, 
  S_ITEMS
from products b
  left join 
    (SELECT prid, SUM(quantity) as P_Items
     FROM p_items
     GROUP BY prid)
     a on b.id = a.prid
  left join 
    (SELECT prid, SUM(quantity) as S_Items
     FROM s_items
     GROUP BY prid)
     c on c.prid = a.prid
group by b.id, b.name

以及更新后的Fiddel:http://sqlfiddle.com/#!2/62b45/12

祝你好运。

如果获得所需答案的最佳方法是使用联合查询,而codeigniter不允许您编写联合查询,则不要使用codeignite器编写查询。将其放入存储过程中,并使用codeigniter调用存储过程。