使用不存在这种方式的数据扩展结果

时间:2019-01-23 17:05:37

标签: mysql

对不起,但我不能说出我的目标的话。 也许有人通过以下示例了解我的问题:

存储的数据:

brand   warehouse   amount
-----------------------
ba      a           1
bb      a           1
ba      b           1
bb      c           1

我想编写一个选择查询,其结果如下:

brand   warehouse   amount
-----------------------
ba      a           1
bb      a           1
ba      b           1
bb      b           null
ba      c           null
bb      c           1

品牌“ bb”不在仓库“ a”中,而是存在于其他仓库中,则无论如何都应列出品牌。

2 个答案:

答案 0 :(得分:2)

似乎我们要生成brandwarehouse的叉积。

这里是一种方法:

获取brand值的独特列表:

SELECT bt.brand 
  FROM stored_data bt
 GROUP BY bt.brand 

获取warehouse值的独特列表:

SELECT wt.warehouse
  FROM stored_data wt
 GROUP BY wt.warehouse

生成这两个集合的笛卡尔乘积(叉积):

SELECT b.brand
     , w.warehouse
  FROM ( SELECT bt.brand
           FROM stored_data bt
          GROUP BY bt.brand
       ) b
 CROSS
  JOIN ( SELECT wt.warehouse
           FROM stored_data wt
          GROUP BY wt.warehouse
       ) w
 ORDER 
    BY b.brand
     , w.warehouse

下一步是获取amount列的外部联接。如果(brand,warehouse)元组在stored_data中是唯一的,那么我们可以这样做:

SELECT b.brand
     , w.warehouse
     , a.amount
  FROM ( SELECT bt.brand
           FROM stored_data bt
          GROUP BY bt.brand
       ) b
 CROSS
  JOIN ( SELECT wt.warehouse
           FROM stored_data wt
          GROUP BY wt.warehouse
       ) w
  LEFT
  JOIN stored_data a
    ON a.brand     = b.brand
   AND a.warehouse = w.warehouse
 ORDER 
    BY b.brand
     , w.warehouse

如果(brand,warehouse)不是唯一的,则查询有可能返回具有相同品牌和仓库值的多行。

如果我们要折叠行并得到总计amount,则规范模式是使用GROUP BY和聚合函数:

SELECT b.brand
     , w.warehouse
     , SUM(a.amount) AS amount
  FROM ( SELECT bt.brand
           FROM stored_data bt
          GROUP BY bt.brand
       ) b
 CROSS
  JOIN ( SELECT wt.warehouse
           FROM stored_data wt
          GROUP BY wt.warehouse
       ) w
  LEFT
  JOIN stored_data a
    ON a.brand     = b.brand
   AND a.warehouse = w.warehouse
 GROUP
    BY b.brand
     , w.warehouse
 ORDER 
    BY b.brand
     , w.warehouse

还有其他可能实现的查询模式和等效的结果。

答案 1 :(得分:0)

如果没有Warehouse表,请使用stored_data制作一个

SELECT
    D.brand,
    W.warehouse
FROM
    (Select 
        DISTINCT warehouse
    FROM stored_data
    ) W LEFT JOIN stored_data D on W.warehouse = D.warehouse
ORDER By D.brand, D.warehouse