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.