连接不同表结构的SQL(MSSQL)
我有不同的表,我想加入所有的信息。在我的例子中,我有一个产品、销售和产品定义表 产品表:连接不同表结构的SQL(MSSQL),sql,sql-server,select,join,Sql,Sql Server,Select,Join,我有不同的表,我想加入所有的信息。在我的例子中,我有一个产品、销售和产品定义表 产品表: ProductID | Name 1 | Product 1 2 | Product 2 3 | Product 3 产品定义表: DefID | ProductID | Column 1 | Column 2 | .... 001 | 1 | text | text 002 | 1
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 | - | -
尝试使用
ISNULL
函数:
select ISNULL(DefID, -1) as DefID, ProductID,
ISNULL(SalesID,-1) as SalesID, ISNULL(Sales,-1) as Sales,
other columns...
from
试试这个:
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
问题是关于连接表,而不是关于NULL