代码之家  ›  专栏  ›  技术社区  ›  Oskar Kjellin

普适性SQL 10将一个表连接到另一个表上

  •  0
  • Oskar Kjellin  · 技术社区  · 14 年前

    我有一张摆着产品的桌子。
    当我从那张表中得到信息时,我还想得到那篇文章的预计到达时间。为此,我计划获取最新的采购订单行,即本文中的行,然后获取此采购的预期交付。

    这是三个不同的表,我希望它像查询中的另一列一样,所以我可以像在同一个表中那样从该列中获取值。

    我的想法可行吗?如果本文没有采购订单,我希望该值为空。

    产品

    Int ProductId
    Int Price
    

    样本数据

    ProductId  Price
    -----------------
    1          100
    2          300
    

    波尔多

    Int RowId
    Int ProductId
    Int POId
    

    样本数据

    RowId  ProductId  POId
    -----------------------
    1      1          1
    

    人事军官

    Int POId
    DateTime ETA
    

    样本数据

    POId  ETA
    -----------------------
    1     2010-10-25 10:05
    

    所以我想要的结果是:

    ProductId   Price  ETA (null if no rows exist)
    ------------------------------------------------
    1           100    2010-10-25 10:05
    2           300    NULL
    
    2 回复  |  直到 14 年前
        1
  •  0
  •   OMG Ponies    14 年前

       SELECT p.productid,
              p.price,
              x.max_eta
         FROM PRODUCTS p
    LEFT JOIN POROWS r ON r.productid = p.productid
    LEFT JOIN (SELECT po.id,
                      MAX(po.eta) AS max_eta
                 FROM PO po 
             GROUP BY po.id) x ON x.poid = r.poid
    

        2
  •  0
  •   Tim    14 年前

    select Products.id, products.name, ProductETAS.ETA
    from Products
    left join
    
    ( 
      select POLINES.productid, min(PO.ETA) as ETA from PO inner join POLINES
       on PO.id = POLINES.POid and POLINES.productid = ?
       where PO.ETA >= today 
       group by POLINES.productid
     ) as ProductETAS
    
     on Products.productid = ProductETAS.productid
    
    推荐文章
    JimmyNeutron  ·  actian JCL示例
    7 年前