2

need a small help to figure out this situation. I see that codeigniter is not supporting UNION and i want to figure out this method to get the total sum for 2 tables, with same id of product.

The issue is that on sum 2 tables, the values are duplicating or multiplicative.

Link to SQL Fiddle

Structure :

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);

Execute in normal 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;

Codeigniter Function:

$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();

Any help is very appreciated.

4

2 回答 2

3

您的问题是您生产笛卡尔积并因此得到重复的总和。以产品 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

祝你好运。

于 2013-02-09T20:00:40.003 回答
0

如果获得所需答案的最佳方法是使用联合查询,而 codeigniter 不允许您编写查询,请不要使用 codeigniter 来编写查询。把它放在一个存储过程中,用codeigniter调用这个存储过程。

于 2013-02-09T21:02:28.410 回答