SQL加入不同的表结构(MSSQL)

时间:2016-04-19 07:49:01

标签: sql sql-server select join

我有不同的表格,我想加入所有信息。就我而言,我有一个产品,销售和产品定义表。

产品表:

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

销售表:

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  |    -     |    -  

我想用-1替换不存在的信息(例如产品定义 - >销售)。并创建一个查询来获取此视图:

GET https://www.googleapis.com/youtube/v3/search?part=id&channelId=UCIiJ33El2EakaXBzvelc2bQ&type=video&key={YOUR_API_KEY}

SQL Fiddle example

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

尝试使用ISNULL功能:

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