【问题标题】:SQL Joining different tables structure (MSSQL)SQL 连接不同的表结构 (MSSQL)
【发布时间】:2016-08-11 05:57:22
【问题描述】:

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

产品表:

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

【问题讨论】:

    标签: sql sql-server select join


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

      【解决方案2】:

      尝试使用ISNULL函数:

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

      【讨论】:

      • 问题是关于连接表,而不是关于 NULL
      猜你喜欢
      • 2021-01-20
      • 1970-01-01
      • 2017-01-08
      • 2011-12-04
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      相关资源
      最近更新 更多