检查2个表是否具有相同的ID,如果表2中存在表1中的ID,则在列中返回1/0

时间:2020-07-28 17:59:27

标签: sql postgresql

我有2个表,其中1个表包含所有预订ID,1个表包含直播预订的预订ID。我正在尝试编写一个查询,检查直播表中是否存在预订ID,如果为true,则返回“ 1”,如果为false,则返回“ 0”。我认为最好的方法是使用case语句,如果保留ID存在于实时流表中,则该语句返回我的结果,但是我遇到了问题。有更好的方法吗?

with table_name as(

select
    reservation_id
from all_reservations 
)

select t.*,
    case when exists(l.reservation_id)
    then '1'
    else '0' end as is_livestream
from livestream_reservations l
left join table name t
    on l.reservation_id = t.reservation_id

2 个答案:

答案 0 :(得分:1)

只要reservation_idlivestream_reservations中最多显示一条记录,这将对您有用:

select r.*,
       case
         when l.reservation_id is null then 0
         else 1
       end as is_livestream
  from reservations r
       left join livestream_reservations l
              on l.reservation_id = r.reservation_id;

case依赖于以下事实:如果未能加入livestream_reservations,则该表的所有列都会返回null

如果reservation_id表中的同一行livestream_reservations可能有多于一行,那么您可以这样做:

with ls_count as (
  select reservation_id, count(*) as count_livestream
    from livestream_reservations
   group by reservation_id
)
select r.*, coalesce(lc.count_livestream, 0) as count_livestream
  from reservations r
       left join ls_count lc on lc.reservation_id = r.reservation_id;

答案 1 :(得分:0)

我会推荐exists并使用布尔值:

select r.*,
       (exists (select 1 from livestream_reservations lr where lr.reservation_id = r. reservation_id)
       ) as is_livestream
from reservations r;

这很有可能比其他解决方案要快。更重要的是,它避免了livestream_reservations中重复项的问题。