SQL语句中的NULL ID

时间:2019-05-06 19:43:09

标签: sql postgresql

Select *
from tbl
where id =  '1fa3bcdc9a1cf60f02a2ae774e2cf166'
  or matching_id = 'ea74c270-65fd-46d0-898b-faf1a7bf7e16'

下面的我的id列针对我的一个事件返回了NULL。它们使用matching_id键关联。有没有办法写一个case语句来填充该id字段,使其不为NULL?

enter image description here

4 个答案:

答案 0 :(得分:0)

您可以使用coalesce(),并在null id的情况下为匹配id的{​​{1}}获取一个值(任何值?):

matching_id

编辑。
如果值未知,请尝试以下操作:

Select 
  coalesce(
    id, 
    (select max(id) from tbl where matching_id = 'ea74c270-65fd-46d0-898b-faf1a7bf7e16')
  ) as id,
  matching_id,
  event_name
from tbl
where 
  id =  '1fa3bcdc9a1cf60f02a2ae774e2cf166'
  or 
  matching_id = 'ea74c270-65fd-46d0-898b-faf1a7bf7e16'

答案 1 :(得分:0)

您可以为此使用ISNULL()函数。也许像这样:

Select 
    ISNULL(id, matching_id) AS [myid],
    matching_id,
    event_name
from tbl
where id =  '1fa3bcdc9a1cf60f02a2ae774e2cf166'
  or matching_id = 'ea74c270-65fd-46d0-898b-faf1a7bf7e16'

答案 2 :(得分:0)

最终写了这样的东西。

[快照1

with find_event AS (
  Select tbl1. id, tbl1.matching_id
  from tbl1 
  where tbl1.id IS NOT NULL
  )

Select
  CASE WHEN find_event. id IS NOT NULL
    THEN find_event. id
  WHEN find_event.id IS NULL
    THEN tbl2. id
  ELSE tbl2. id
END as final_id,

  tbl2.matching_id,
  tbl2. id,
  tbl2.event_name,
  find _event. id as find_canonical_id
from tbl2 
left JOIN find_event on find_event.matching_id = tbl2.matching_id
where    
    tbl2.transaction_canonical_id =  '1fa3bcdc9a1cf60f02a2ae774e2cf166'
  or
  tbl2.matching_id = 'ea74c270-65fd-46d0-898b-faf1a7bf7e16'

答案 3 :(得分:0)

如果要将列值替换为参数中的值,则可以使用以下内容:

with ids (id, mid) as (
  values 
    ('1fa3bcdc9a1cf60f02a2ae774e2cf166', 'ea74c270-65fd-46d0-898b-faf1a7bf7e16')
)
Select coalesce(tbl.id, ids.id), 
       tbl.matching_id, 
       tbl.event_name
from tbl
  join ids on ids.id = tbl.id or ids.mid = tbl.matching_id;