2016-04-19 71 views
2

我有不同的表,我想加入所有信息。在我的情況下,我有一個產品,銷售和產品定義表。SQL加入不同的表結構(MSSQL)

產品表:

ProductID | Name 
    1 | Product 1 
    2 | Product 2 
    3 | Product 3 

產品定義表:

DefID | ProductID | Column 1 | Column 2 | .... 
001  | 1  | text | text 
002  | 1  | text | text  
003  | 3  | text | text 
004  | 2  | text | text 
005  | 3  | text | text 

銷售表:

SalesID | ProductID | Sales 
01  | 1  | 13 
02  | 1  | 12  
03  | 2  | 1 
04  | 2  | 4 
05  | 3  | 2 

我想更換的信息(如產品的定義 - >銷售部),其不存在-1。並創建一個查詢來獲取這樣的觀點:

DefID | ProductID | SalesID | Sales | Column 1 | Column 2 | .... 
001  | 1  | -1  | -1 | text | text 
002  | 1  | -1  | -1 | text | text 
003  | 3  | -1  | -1 | text | text 
004  | 2  | -1  | -1 | text | text 
005  | 3  | -1  | -1 | text | text 
-1  | 1  | 01  | 13 | -  | - 
-1  | 1  | 02  | 12 | -  | -  
-1  | 1  | 03  | 1 | -  | - 
-1  | 2  | 04  | 4 | -  | - 
-1  | 3  | 05  | 2 | -  | - 

SQL Fiddle example

回答

-1

嘗試使用ISNULL功能:

select ISNULL(DefID, -1) as DefID, ProductID, 
     ISNULL(SalesID,-1) as SalesID, ISNULL(Sales,-1) as Sales, 
     other columns... 
from 
+1

的問題是有關連接表,而不是NULL – Mark

2

試試這個:

select DefID, ProductID, -1 as SalesID, -1 as Sales, Column1 , Column2 
from productDefinition 
union all 
select -1 as DefID, ProductID, SalesID,Sales, '-' as Column1 ,'-' as Column2 
from sales