Click here to Skip to main content
15,888,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
problem

the statement below return values without any problem

SQL
select top 1000000  p.PartNumber,m.Supplier,m.TradeCodeType,m.status from #PartsMissed m 
inner join parts.Nop_Part p   on p.CompanyID=m.SupplierId 
where
(p.PartID not in (SELECT PartID FROM parts.TradeCodes t where t.CodeTypeID=m.TradeCode))


I try to do above statement with left join direct but it not return any
values
it return null why
SQL
create table #PartsMissed
(
Supplier    nvarchar(200),
SupplierId  int,
TradeCodeType  nvarchar(100),
TradeCode  int,
status      NVARCHAR(100) NULL
)


insert into #PartsMissed
( 
	SupplierId,
	TradeCode
 )  
    VALUES

	(1000234,849774)


What I have tried:

statement below return null result why
although the first statement using ( not in ) work perfect

SQL
SELECT  p.PartID, p.CompanyID
FROM   parts.Nop_Part      p 
LEFT OUTER JOIN (
     SELECT mp.PartID, mp.CompanyID,d.TradeCode
     FROM parts.Nop_Part mp  left join #PartsMissed d on mp.CompanyID=d.SupplierId 
     left JOIN parts.TradeCodes AS t  ON t.CodeTypeID = d.TradeCode
) x ON p.PartID=x.PartID
WHERE x.PartID is  NULL
Posted
Updated 28-Jan-20 9:03am
v3

Well ... it can't return anything else ...
SQL
SELECT  p.PartID, ...

SQL
LEFT OUTER JOIN (
   ...
) x ON p.PartID=x.PartID

SQL
WHERE x.PartID is  NULL
Since x.PartID must be NULL, and x.PartID must be equal to p.PartID, the only values it can return are NULL.
 
Share this answer
 
Comments
Richard Deeming 28-Jan-20 14:56pm    
That's not how a LEFT JOIN works. :)
Simplify your second query, and the problem should be obvious:
SQL
SELECT
    ...
FROM
    parts.Nop_Part As p
    LEFT JOIN
    (
        SELECT mp.PartID
        FROM parts.Nop_Part As mp
    ) As x
    ON x.PartID = p.PartID
WHERE
    x.PartID Is Null
Or, putting that a different way:
SQL
SELECT
    ...
FROM
    parts.Nop_Part As p
WHERE
    Not Exists
    (
        SELECT 1
        FROM parts.Nop_Part As mp
        WHERE mp.PartID = p.PartID
    )
How many parts are there going to be in your table which don't exist in the same table? :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900