質問

I have 3 tables:

DECLARE @PRODUCT TABLE(PRODUCTID INT,TITLE NVARCHAR(MAX),BRANDID INT,SPECID INT)

DECLARE @SPEC TABLE(SPECID INT,TITLE NVARCHAR(MAX))

DECLARE @BRAND TABLE(BRANDID INT,TITLE NVARCHAR(MAX))

INSERT INTO @PRODUCT 
SELECT 1,'TV',1,8 UNION ALL 
SELECT 2,'PC',2,12

INSERT INTO @BRAND
SELECT 1,'SAMSUN' UNION ALL
SELECT 2,'GRUNDING'

INSERT INTO @SPEC 
SELECT 8,'PRICE' UNION ALL
SELECT 9,'WEIGHT'

I want to get result from @PRODUCT table if at least one of @BRAND or @SPEC tables have data. So I tried with LEFT JOIN like this:

SELECT  p.* ,
        s.*,
        b.*
FROM    @PRODUCT p
         LEFT JOIN @BRAND b ON b.BRANDID = p.BRANDID AND b.BRANDID IS NOT NULL
         LEFT JOIN @SPEC s ON s.SPECID = p.SPECID AND s.SPECID IS NOT NULL

but couldn't get desired result. For data I provided I want to filter only product with Title TV. So, I want to apply optional join. I mean if @BRAND or @SPEC table have data, or both of them have data, it should filter products based on that conditions.

Can anyone help me to solve this problem?

EDIT As per requst I provide more data for tables.

INSERT INTO @PRODUCT 
SELECT 1,'TV',1,8 UNION ALL 
SELECT 2,'PC',2,12 UNION ALL
SELECT 2,'PHONE',505,10

INSERT INTO @BRAND
SELECT 1,'SAMSUN' UNION ALL
SELECT 2,'GRUNDING' 

INSERT INTO @SPEC 
SELECT 8,'PRICE' UNION ALL
SELECT 9,'WEIGHT' UNION ALL
SELECT 10,'SIZE' 

For this data I want to get only row for Product with ProductID=1. So, I need only to select this one row in this example.

役に立ちましたか?

解決

Following works. I just tried it. The only thing I have changed is move WHERE s.SPECID IS NOT NULL from ON CLAUSE to WHERE CLAUSE. Having it in the ON CLAUSE of a LEFT JOIN only restricts it for the join but still returns the row. Having it in the WHERE CLAUSE filters the row.

 DECLARE @SpecCount INT 
 DECLARE @BrandCount INT 

 SELECT @SpecCount = COUNT(*) FROM @SPEC 
 SELECT @BrandCount = COUNT(*) FROM @BRAND 

 SELECT p.*, 
     s.*, 
     b.* 
 FROM @PRODUCT p 
 LEFT JOIN @BRAND b 
     ON b.BRANDID = p.BRANDID 
 LEFT JOIN @SPEC s 
     ON s.SPECID = p.SPECID 
 WHERE ((s.SPECID IS NOT NULL OR @SpecCount = 0) 
     AND (b.BRANDID IS NOT NULL OR @BrandCount = 0))

他のヒント

If I understand what you're looking for correctly, you should do the joins first then filter. Something like:

SELECT
    p.* ,
    s.*,
    b.*
FROM
    @PRODUCT p
LEFT JOIN
    @BRAND b
ON
    b.BRANDID = p.BRANDID
LEFT JOIN
    @SPEC s
ON
    s.SPECID = p.SPECID
WHERE
    b.BRANDID IS NOT NULL OR s.SPECID IS NOT NULL
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top