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

wj8zmpe1  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(379)

我有两个表,一个包含所有预订ID,一个包含livestream预订的预订ID。我正在尝试编写一个查询,检查livestream表中是否存在保留id,如果为true,则返回“1”;如果为false,则返回“0”。我认为最好的方法是使用case语句,如果livestream表中存在reservation 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
2ic8powd

2ic8powd1#

只要 reservation_id 最多出现一张唱片 livestream_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_idlivestream_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;
v7pvogib

v7pvogib2#

我建议你 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 .

相关问题