2017-08-11 101 views
0

我有一個引用三個表的查詢。SQL加入查詢返回空

的表格如下所示:

FORM_FACTOR

FORM_FACTOR_ID | FORM_FACTOR_DESCRIPTION 

AOF_ORDER_LINE_QUEUE

SO_LINE_NUMBER | FORM_FACTOR_ID 

AOF_ORDER_PARTS

SERIAL_NUMBER | SO_LINE_NUMBER 

想法是使用零件的SERIAL_NUMBER得到FORM_FACTOR_DESCRIPTION。我寫了一個查詢來做到這一點,但無論出於何種原因,它都返回null。我可以發誓這個查詢正在工作,但顯然有一個缺陷。幫助表示讚賞。

查詢:

DECLARE @serial VARCHAR(50) 
SET @serial = 'somestring' 

SELECT 
    ff.[FORM_FACTOR_DESCRIPTION] 
FROM 
    [dbo].[FORM_FACTOR] AS ff 
JOIN 
    [dbo].[AOF_ORDER_LINE_QUEUE] AS lQ ON ff.[FORM_FACTOR_ID] = lQ.[FORM_FACTOR_ID] 
JOIN 
    [dbo].[AOF_ORDER_PARTS] AS oO ON oO.[SO_LINE_NUMBER] = lQ.[SO_LINE_NUMBER] 
WHERE 
    oO.[SERIAL_NUMBER] = @serial 
+4

它可能沒有返回行,而不是'NULL'。最可能的原因是'WHERE'沒有匹配。接下來最有可能的原因是'JOIN's沒有匹配。 –

+0

您是否錯過了第二行開頭的SET或SELECT命令?換句話說,SET @serial ='something'; –

+0

在AOF_Order_parts中不存在@serial;或者它和so_Line_Number它關聯doens不存在於lq.form_factor_ID中,或者它確實存在,但是form_Facotr_ID dof不存在於ff中。這似乎是一個數據問題而不是查詢。 – xQbert

回答

0

不是一個真正的解決方案在這裏。在這一點上它仍然是一個未解之謎。

但要尋找根本原因,也許你可以打開連接並使用左連接?
也許更容易發現連接在右側返回NULL的位置。

在下面的例子中,我迷惑了COLLATION。 只是忽略並刪除它,很可能它與它無關。

DECLARE @serial VARCHAR(50); 
SET @serial = 'EOXH2T100008' ; 

SELECT DB_NAME() as current_db, DATABASEPROPERTYEX(DB_NAME(), 'Collation') as db_collation; 
--#SQL_Latin1_General_CP1_CI_AS 
--SELECT Name, Description FROM fn_helpcollations() where name like '%Latin1%' ; 

declare @FORM_FACTOR table (FORM_FACTOR_ID int, FORM_FACTOR_DESCRIPTION varchar(30)); 
insert into @FORM_FACTOR (FORM_FACTOR_ID, FORM_FACTOR_DESCRIPTION) values (1,'test 1'),(2,'test 2'); 

declare @AOF_ORDER_LINE_QUEUE table (ORDER_LINE_QUEUE_ID int identity(1,1), FORM_FACTOR_ID int, SO_LINE_NUMBER int); 
insert into @AOF_ORDER_LINE_QUEUE (FORM_FACTOR_ID, SO_LINE_NUMBER) values (1,100),(3,100),(2,200); 

declare @AOF_ORDER_PARTS table (ORDER_PARTS_ID int identity(1,1), SO_LINE_NUMBER int, SERIAL_NUMBER VARCHAR(50) COLLATE SQL_Latin1_General_CP850_BIN); 
insert into @AOF_ORDER_PARTS (SO_LINE_NUMBER, SERIAL_NUMBER) values (100,'EOXH2T100008'),(200,'eOXH2T100008'); 

SELECT 
oO.ORDER_PARTS_ID, oO.SERIAL_NUMBER, oO.SO_LINE_NUMBER, 
lQ.ORDER_LINE_QUEUE_ID, lQ.FORM_FACTOR_ID, 
ff.FORM_FACTOR_DESCRIPTION 
FROM @AOF_ORDER_PARTS AS oO 
LEFT JOIN @AOF_ORDER_LINE_QUEUE AS lQ ON lQ.[SO_LINE_NUMBER] = oO.[SO_LINE_NUMBER] 
LEFT JOIN @FORM_FACTOR AS ff ON ff.[FORM_FACTOR_ID] = lQ.[FORM_FACTOR_ID] 
WHERE oO.[SERIAL_NUMBER] = @serial;