【问题标题】:How to join a table to the result from a union query如何将表连接到联合查询的结果
【发布时间】:2020-06-05 09:17:10
【问题描述】:

我正在使用 union select 从 2 个表中选择数据:

select Product_Code from Discount_Table union select Product_Code from Discount2_Table 

Union Query returns this

所以在我选择数据后,我想使用这些数据与其他表连接,例如 Product_Table,但我遇到了错误。

这是我的查询

select Product_Name, Price
from Discount_Table
union
select Product_Code
from Discount2_Table
join Product_Table on Discount_Table.Product_Code = Product_Table.Product_Code

任何提示/帮助将不胜感激!

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    你可以像这样使用子查询:

    SELECT * FROM 
    
    (select Product_Name,Price from Discount_Table union select Product_Code from Discount2_Table) Discount_Table
    
    JOIN Product_Table ON Discount_Table.Product_Code = Product_Table.Product_Code
    

    【讨论】:

      【解决方案2】:

      您可以通过几种不同的方式稍后在查询中引用结果表,但这里有几种: 您可以将第一个查询的结果放入 CTE (Common Table Expression),然后在代码中进一步加入:

      WITH product_codes (Product_code) AS
          (
              select Product_Code 
              from Discount_Table 
      
              union
      
              select Product_Code 
              from Discount2_Table 
          )
          select t.Product_Name, t.Price  
          from product_codes pc
          join Product_Table t on pc.Product_Code = t.Product_Code
      

      你也可以使用temporary tables:

      select Product_Code 
      INTO #product_codes
      from Discount_Table 
      
      union
      
      select Product_Code 
      from Discount2_Table 
      
      select t.Product_Name, t.Price  
      from #product_codes pc
      join Product_Table t on pc.Product_Code = t.Product_Code
      

      通过将您的第一个查询的结果存储到一个临时表中,您可以稍后在查询中访问该临时表,其工作原理类似。您选择一个版本而不是另一个版本的原因有很多,但它们都足以让您获得结果。 我找到了一个很好的答案,更多地解释了这些差异here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-28
        • 1970-01-01
        • 2023-02-06
        相关资源
        最近更新 更多