具有不同行数的MYSQL连接相关表每"记录"

时间:2016-08-25 15:03:35

标签: mysql

表A是Orders表,每个订单有1行。表B是Items表,每个项目有1行。它们通过订单号链接。当我在这个O / N上加入他们时,如果订单上有超过1个项目,我会收到多行订单。我正在按不同表中的字段进行分组,因此我无法使用该方法。

加入它们的正确方法是什么,1订单行和3个项目行不会变成3个订单和3个项目?

对于基本问题道歉,我的大脑今天正在崩溃。

我用以下内容简化了我的要求。

CREATE TABLE Orders
    (`ORDURN` varchar(8), `ORDSOU` varchar(10), `ORDVAL` decimal(9,2))
;

INSERT INTO Orders
    (`ORDURN`, `ORDSOU`, `ORDVAL`)
VALUES
    ('12345112', 'WEB', '28.41'),
    ('22544548', 'ADVERT', '11.58'),
    ('44848643', 'TELEPHONE', '41.18')
;


CREATE TABLE Items
    (`ITMSTK` varchar(10), `ITMQTY` varchar (3), `ITMCOG` int(9), `ITMURN` varchar(8), `ITMSOU` varchar(10))
;

INSERT INTO Items
    (`ITMSTK`, `ITMQTY`, `ITMCOG`, `ITMURN`, `ITMSOU`)
VALUES
    ('WN778', '1', '2.00', '12345112', 'WEB'),
    ('WN776', '1', '1.45', '12345112', 'WEB'),
    ('WN771', '1', '1.86', '12345112', 'WEB'),
    ('WN845', '1', '1.45', '22544548', 'ADVERT'),
    ('WN846', '1', '1.38', '22544548', 'ADVERT'),
    ('WN845', '1', '20.16', '44848643', 'TELEPHONE')
;
CREATE TABLE Sources
    (`SOUCOD` varchar(10), `SOUDESC` varchar(45))
;
INSERT INTO Sources 
    (`SOUCOD`, `SOUDESC`)
VALUES
    ('WEB', 'Web Orders 2016'),
    ('ADVERT', 'Advert Junes 2016'),
    ('TELEPHONE', 'Telephone Orders 2016')
;

然后我在下面运行此查询

    select
S.soucod as Sources,
s.soudesc as Description,
sum(i.itmcog) as COG,
count(DISTINCT o.ordurn) as Orders,
sum(o.ordval) as OrderValue
from sources s
join orders o on o.ordsou = s.soucod
join items i on i.itmsou = s.soucod
group by s.soucod

给我

Sources     Description           COG   Orders  OrderValue  
ADVERT      Advert Junes 2016       2        1       23.16
TELEPHONE   Telephone Orders 2016  20        1       41.18
WEB         Web Orders 2016         5        1       85.23

显然,由于连接已经计算了多行

,因此连接会使订单值出现偏差

这是理想的结果(商品成本是错误的,但我知道为什么会这样,就像我创建数据的方式一样,这个专栏不是出于任何目的而是为了表明需要引入项目表):

Sources     Description           COG   Orders  OrderValue  
ADVERT      Advert Junes 2016       2        1       11.58
TELEPHONE   Telephone Orders 2016  20        1       41.18
WEB         Web Orders 2016         5        1       28.41

我希望这可以解释它。

2 个答案:

答案 0 :(得分:1)

需要顺序连接并计算中间结果。在连接的外层使用max()函数对子查询的结果。

select Sources, Description,
       sum(i.itmcog) as COG,
       max(Orders) as Orders, max(OrderValue) as OrderValue
  from (
        select s.soucod as Sources, s.soudesc as Description, 
               count(o.ordurn) as Orders,
               sum(o.ordval) as OrderValue
          from sources s
          join orders o on o.ordsou = s.soucod
         group by s.soucod
       ) A
   join items i on i.itmsou = A.Sources
  group by A.Sources

如果只从依赖表中选择一个结果,则可以在选择列表中使用子查询:

select s.SOUCOD as Sources, s.soudesc as Description, 
       (select sum(i.itmcog)
          from items i
         where i.itmsou=s.soucod
       ) as COG,
       count(o.ordurn) as Orders,
       sum(o.ordval) as OrderValue
  from sources s
  join orders o on o.ordsou = s.soucod
 group by s.soucod

答案 1 :(得分:0)

{{1}}