Question : Problem with SQL Statment

Hi, in the following SQL statenment if the [key] and [value] columns are null  the sql statenment will not retrieve its corresponding row(s), how can I modify it to make it retrieves the row even if these valus are null.
pLEASE NOTE MY db ENGINE IS sql SERVER
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
SELECT IEI.[Key], IEI.Value ,II.CSS_Class, II.Control_Type, II.ID as ICF_ID
	FROM Item_Extra_Info AS IEI
	LEFT JOIN Item_Category_Form AS II ON II.ID = IEI.Item_Category_Form_FK 
	WHERE IEI.Item_Category_Form_FK  
	IN
		(SELECT ICF.ID 
		FROM Item_Category_Form AS ICF
		LEFT JOIN Item_Category AS IC ON ICF.Item_Category_FK = IC.ID
		LEFT JOIN Item AS I ON I.Item_Category_FK = IC.ID
		WHERE  I.ID = IEI.Item_FK AND I.ID = 2)

Answer : Problem with SQL Statment

Since the "key" and "value" columns are the only ones coming from the first table in the query, I would suspect what you are seeing is not just that they are NULL but there is no row for that table.  If you truly want to see the other data even when there is no match in the first table then you need to either switch the order of the tables or use a RIGHT JOIN.

SELECT IEI.[Key], IEI.Value ,II.CSS_Class, II.Control_Type, II.ID as ICF_ID
FROM Item_Extra_Info AS IEI
RIGHT JOIN Item_Category_Form AS II ON II.ID = IEI.Item_Category_Form_FK
WHERE II.ID IN (
  SELECT ICF.ID
   FROM Item_Category_Form AS ICF
  INNER JOIN Item_Category AS IC ON ICF.Item_Category_FK = IC.ID
  INNER JOIN Item AS I ON I.Item_Category_FK = IC.ID
  WHERE  I.ID = 2
)

;

I made some alterations also as follows:
+II.ID in the WHERE clause other-wise you are in essence doing an INNER JOIN as IEI row would have to exist to fit the WHERE...IN criteria.  Since JOIN shows that II.ID = IEI.Item_Category_Form_FK, my change should be equivalent.
+LEFT JOIN's in the sub query made no sense as you are ultimately filtering on the Item (I) table and so the result is an INNER JOIN.  
+Additionally, since IEI is no longer the focal point I took a chance removing the correlation to IEI.Item_FK hoping since there is an explicit ID = 2 that the proper results are met anyway.

Hope this helps at least give you an idea what kinds of things would need to change if this is not the final query you need as it stands.

Best regards and happy coding,

--isa
Random Solutions  
 
programming4us programming4us