2016-05-12 34 views
-1

我提出兩個選擇語句與不同的結果集, 請幫我做這兩個SELECT語句顯示其結果在一個表中,SQL Server中,如何創建一個表中的兩個select語句

DECLARE @EmpID INT 

SELECT @EmpID = SubCategoryId 
FROM dbo.Product 
WHERE ProductId = 13 

SELECT Product.ProductId 
    , Product.ProductName 
    , Product.ProductPrice 
    , Product.ProductQuantity 
    , Product.SubCategoryId AS ForUpdate 
    , SubCategory.SubCategoryName 
    , SubCategory.SubCategoryId 
FROM Product 
INNER JOIN ProductUnderCategory 
    ON ProductUnderCategory.ProductId = Product.ProductId 
INNER JOIN SubCategory 
    ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId 
WHERE Product.ProductId = 13 

SELECT Property.Propertyid 
    , Property.PropertyName 
    , ProductProperties.PropertyValue 
FROM Property 
LEFT JOIN ProductProperties 
    ON Property.PropertyId = ProductProperties.PropertyId AND ProductProperties.ProductId = 13 
WHERE Property.Propertyid IN (
     SELECT PropertyId 
     FROM CategoryProperty 
     WHERE CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId AND CategoryProperty.SubCategoryId = @EmpID 
     ) 
+2

您是使用mySQL還是MS SQL Server?你有兩個標籤。 – Morpheus

+0

你想合併來自兩個結果集的所有行嗎?如果是這樣,列將需要「排隊」,並且沒有相同數量的列被返回。 – Morpheus

+0

如果這是SQL Server(我不知道關於mysql),那麼你將需要一個聯盟,但作爲Morpheus說這兩個查詢的列需要匹配。 – OldBoyCoder

回答

0

我假設你想要每個產品的屬性(不是聯合,而是聯接)。類似這樣的:

DECLARE @EmpID INT 

SELECT @EmpID = SubCategoryId 
FROM dbo.Product 
WHERE ProductId = 13 

SELECT Product.ProductId 
    , Product.ProductName 
    , Product.ProductPrice 
    , Product.ProductQuantity 
    , Product.SubCategoryId AS ForUpdate 
    , SubCategory.SubCategoryName 
    , SubCategory.SubCategoryId 
    , Property.Propertyid 
    , Property.PropertyName 
    , ProductProperties.PropertyValue 
FROM Product 
INNER JOIN ProductUnderCategory 
    ON ProductUnderCategory.ProductId = Product.ProductId 
INNER JOIN SubCategory 
    ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId 
LEFT JOIN ProductProperties 
    on ProductProperties.ProductID = Product.ProductID 
left join Property 
    ON Property.PropertyId = ProductProperties.PropertyId 
    and Property.Propertyid IN (
     SELECT PropertyId 
      FROM CategoryProperty 
      WHERE 
       CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId 
       AND CategoryProperty.SubCategoryId = @EmpID 
      ) 
WHERE Product.ProductId = 13 
+0

它的工作,非常感謝Chris Steele,上帝保佑你! – Lucy

0

您可能可以執行以下操作 - 如果第一個選擇中不存在列,則需要包含任何適合的值,並且必須命名該列。如果後續選擇中不存在列,則只需返回null /''/ 0或任何您需要的值作爲值;

select Product.ProductId, Product.ProductName, Product.ProductPrice, Product.ProductQuantity, '' as someColumn, .... 
from .... 
union [all] 
Select Property.Propertyid, Property.PropertyName, ProductProperties.PropertyValue, NULL (for ProductQuantity), ProductProperties.someColumn 
from ..... 
相關問題