【问题标题】:How to join a SQL Server table that has Null Values?如何加入具有空值的 SQL Server 表?
【发布时间】:2017-08-03 18:33:32
【问题描述】:

我编写了代码来查询特定帐号注册了多少车牌。它还提供了该车辆的品牌。

我使用 4 个表来获取此信息:

  1. 账户表
  2. 盘子桌
  3. VehClass 表(用于描述车辆类型。例如:汽车、卡车等)
  4. VehicleMake 表(字段为 VehicleMakesID 和 VehicleMakeDesc

问题是,Plate 表。很多条目在 VehicleMakeID 字段。因此无法加入 VehicleMake 表以获取 车辆描述。

我的代码如下:

select ac.AccountNumber
    , p.LicPLateno
    , p.LicPlateState
    , p.LicPlateCountry
    , vm.VehicleMakeDesc
    , p.VehicleModel
    , p.VehicleYear
    , v.VehShortDesc
    --, ISNULL(p.VehicleMakeId,'-1') VechicleMakeId  --(-1 means Other)
    , p.VehicleMakeId

from account ac 
inner join Plate p on ac.AccountId=p.AccountId 
inner join VehClass v on p.VehClassId=v.VehClassID 
inner join VehicleMake vm on p.VehicleMakeId=vm.VehicleMakeId

where ac.AccountNumber= '12345678'
  and p.PlateStatusId=1  --(For Active Plates only)
  and p.EndDate is null  --(Plates are not expired)

order by p.LicPlateNo

我得到的结果是:

ABS123  BC  CA  Other   - NULL  Cars    -1  
DEF345  BC  CA  Other   - NULL  Cars    -1  
GHI456  BC  CA  Other   - NULL  Cars    -1  
HIJ567  BC  CA  Other   - NULL  Cars    -1

结果显示只有 4 个板块,但实际上有 31 个板块。其他车牌没有显示,因为其他车牌在 VehicleMakeID 字段中为 NULL。因此,它们没有加入 VehicleMake 表。

如何获得所有 31 个车牌的列表,如果 VehicleMakeID 为 NULL,那么描述应显示为 Other?

【问题讨论】:

  • 你已经接近了。将您的 isnull 保留在您的 select 语句中,并使用外部连接来获取您的盘子。
  • 左加入VehicleMake

标签: sql sql-server join inner-join


【解决方案1】:

将INNER JOIN 与VehicleMake 表更改为LEFT JOIN:

select ac.AccountNumber
    , p.LicPLateno
    , p.LicPlateState
    , p.LicPlateCountry
    , ISNULL(vm.VehicleMakeDesc,'Other')
    , p.VehicleModel
    , p.VehicleYear
    , v.VehShortDesc
    , ISNULL(p.VehicleMakeId,'-1') VechicleMakeId  --(-1 means Other)
    --, p.VehicleMakeId

from account ac 
inner join Plate p on ac.AccountId=p.AccountId 
inner join VehClass v on p.VehClassId=v.VehClassID 
left join VehicleMake vm on p.VehicleMakeId=vm.VehicleMakeId

where ac.AccountNumber= '12345678'
  and p.PlateStatusId=1  --(For Active Plates only)
  and p.EndDate is null  --(Plates are not expired)

order by p.LicPlateNo
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2021-12-31
    • 2017-05-09
    相关资源
    最近更新 更多