2016-04-19 24 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