2016-05-12 3 views
-1

一つのテーブルに2つのSELECT文を作成するには、 は、私はこれらの2つの選択文が一つのテーブルで彼らの結果を表示するために助けてくださいSQL Serverでは、どのように私は別の結果セットを持つ2つの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についてはわかりません)、UNIONが必要ですが、Morpheusは2つのクエリの列が一致する必要があると述べています。 – 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

おそらく次のようなことができます.1番目の列に列が存在しない場合は、適切な値を含めて列に名前を付ける必要があります。列が後続の選択項目に存在しない場合は、単に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 ..... 
関連する問題