比较sql中的聚合值

svgewumm  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(382)

假设我有三张这样的table:

create table garage (id INT);
create table floor (id INT, garage_id INT);
create table parking_spot (id INT, floor_id INT, is_occupied INT);

我想打印这个问题的答案:车库满了吗?换句话说,所有的景点都被占用了吗?
我知道我可以分别运行以下两个查询。
以下查询提供了车库的总位置:

select count(*) from parking_spot ps
  join floor f on ps.floor_id = f.id
  join garage g on f.garage_id = g.id
  where g.id = 2

下面是车库里被占用的位置:

select count(*) from parking_spot ps
  join floor f on ps.floor_id = f.id
  join garage g on f.garage_id = g.id
  where g.id = 2 and ps.is_occupied = 1;

但是我想编写一个查询来比较这两个sql&打印“garage is full”或“garage is not full”。我该怎么做?

ee7vknir

ee7vknir1#

我喜欢上面@juergen-d给出的答案,但为了完整起见,根据我的要求修改了他的答案:

select
  case when sum(ps.is_occupied = 0) = 0 then 'Garage is full'
       else 'Garage is NOT full'
  end
  from parking_spot ps
    join floor f on ps.floor_id = f.id
    where f.garage_id = 2;

在进一步审查后,似乎“when exists”表现更好,因为不需要计算,所以我接受了@krokodilko给出的答案。在这里:

SELECT CASE WHEN EXISTS (
      select * from parking_spot ps
      join floor f on ps.floor_id = f.id
      where f.garage_id = 1 and ( ps.is_occupied <> 1 OR ps.is_occupied IS NULL )
    ) 
  THEN 'Garage is not full' ELSE 'Garage is full'
END;
uttx8gqw

uttx8gqw2#

select sum(ps.is_occupied = 0) = 0 as is_full
from parking_spot ps
join floor f on ps.floor_id = f.id
where f.garage_id = 2

这个 sum() 为您提供免费插槽的数量。如果是的话 0 那么车库就满了。

e5njpo68

e5njpo683#

您不需要统计所有记录,只需检查是否至少有一个或没有未占用的空间:

SELECT CASE WHEN EXISTS (
      select * from parking_spot ps
      join floor f on ps.floor_id = f.id
      join garage g on f.garage_id = g.id
      where g.id = 2 and ( ps.is_occupied <> 1 OR ps.is_occupied IS NULL )
    ) 
  THEN 'Garage is not full' ELSE 'Garage is full'
END;

相关问题