如何连接来自多个 table 的数据并保持所有不同的值

How to join data from multiple table keeping all distinct values

我有三个 tables :

文章:

idArticle
libArticle

库存:

idArticle
idWarehouse
qtyStock

仓库:

idWarehouse
libWarehouse

在table库存中,我只有货品 因此,例如,如果数据是:

文章:

890001 'Article1'
890002 'Article2'

仓库:

0001 'Warehouse Est'
0002 'Warehouse West'
0003 'Warehouse South'

库存:

890001 0001 50
890001 0002 30
890002 0003 20

我想发出一个请求,显示每件商品的库存数量,如果没有库存,则在数量库存中显示“0”,并且每个仓库各占一行,例如:

890001 0001 50
890001 0002 30
890001 0003 0
890002 0001 0
890002 0002 0
890002 0003 20

我试过了:

select a.idwarehouse, a.idarticle, s.qtystock  from 
(
select idwarehouse, idarticle
from article, warehouse
where idarticle IN ('890001', '890002')
) a 
left join stock s on a.idwarehouse = s.idwarehouse and a.idarticle = s.idarticle

它可以工作,但是有没有更好的方法来完成它而不需要那种子请求?

可以通过简单的CROSS JOIN文章和仓库获得所有组合,然后LEFT JOIN库存来实现结果。

WITH
    article (idarticle, libarticle)
    AS
        (SELECT '890001', 'Article1' FROM DUAL
         UNION ALL
         SELECT '890002', 'Article2' FROM DUAL),
    stock (idarticle, idwarehouse, qtystock)
    AS
        (SELECT '890001', '0001', 50 FROM DUAL
         UNION ALL
         SELECT '890001', '0002', 30 FROM DUAL
         UNION ALL
         SELECT '890002', '0003', 20 FROM DUAL),
    warehouse (idwarehouse, libwarehouse)
    AS
        (SELECT '0001', 'Warehouse Est' FROM DUAL
         UNION ALL
         SELECT '0002', 'Warehouse West' FROM DUAL
         UNION ALL
         SELECT '0003', 'Warehouse South' FROM DUAL)
  SELECT a.idarticle, w.idwarehouse, NVL (s.qtystock, 0) AS stock
    FROM article a
         CROSS JOIN warehouse w
         LEFT JOIN stock s ON (a.idarticle = s.idarticle AND w.idwarehouse = s.idwarehouse)
ORDER BY a.idarticle, w.idwarehouse;



   IDARTICLE    IDWAREHOUSE    STOCK
____________ ______________ ________
890001       0001                 50
890001       0002                 30
890001       0003                  0
890002       0001                  0
890002       0002                  0
890002       0003                 20