ms使用union all和inner join访问sql

时间:2018-04-11 13:13:59

标签: sql ms-access inner-join union-all

我正在尝试编写一个带有union all的sql和一个带有内连接[Code]的字段。

 SELECT TypeID, 
       (SELECT CodeID 
          FROM tblID
          INNER JOIN tblA ON tblID.TypeID = tblA.TypeID) as Code,        
    APrice as 1,         
    Null as 2 
 FROM tblA 
 UNION ALL 
 SELECT TypeID, 
       (SELECT CodeID 
          FROM tblID
          INNER JOIN tblM ON tblID.TypeID = tblM.TypeID) as Code,
    Null as 1,
    MPrice as 2          
 FROM tblM;

2 个答案:

答案 0 :(得分:2)

您的子查询返回多行。据推测,您打算使用相关子查询。那看起来像是:

SELECT TypeID, 
       (SELECT CodeID FROM tblID WHERE tblID.TypeID = tblA.TypeID) as Code,        
       APrice as aprice,         
       Null as mprice
FROM tblA 
UNION ALL 
SELECT TypeID, 
       (SELECT CodeID FROM tblID WHERE tblID.TypeID = tblM.TypeID) as Code,
       Null as aprice,
       MPrice as mprice          
FROM tblM;

注意:

  • 如果您单独运行子查询,则会看到此错误。您应该学习如何调试查询。
  • 我认为数字不是有效的列别名。在任何情况下,它们都是一个糟糕的选择,所以给列添加实名。
  • 此逻辑通常使用inner joinleft join
  • 处理

答案 1 :(得分:1)

我只是在这里猜测你的内部子查询返回多个记录并且它已经全部被抛出。但是,由于您没有共享示例数据或错误消息,所以无法说。

考虑使用LEFT OUTER JOIN(下面)在没有子查询的情况下重写这个,或者切换到正确的相关子查询。

SELECT TypeID
    ,tblID.CodeID
    ,APrice AS 1
    ,NULL AS 2
FROM tblA 
    LEFT OUTER JOIN tblID 
        ON tblID.TypeID = tblA.TypeID

UNION ALL

SELECT TypeID
    ,tblID.CodeID
    ,NULL AS 1
    ,MPrice AS 2
FROM tblM
    LEFT OUTER JOIN tblID 
        ON tblID.TypeID = tblM.TypeID