比较SQL中的汇总值

时间:2018-08-09 16:05:03

标签: mysql sql

假设我有3张这样的桌子:

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);

我想打印以下问题的答案:车库满了吗?换句话说,所有景点都被占用了吗?

我知道我可以分别运行以下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

及以下内容为我提供了车库的已占用插槽数:

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,并显示“车库已满”或“车库未满”。我该怎么做?

3 个答案:

答案 0 :(得分:2)

您不需要计算所有记录,只需检查是否至少有一个或没有一个空位即可。

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;

答案 1 :(得分:1)

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,则说明车库已满。

答案 2 :(得分:0)

我喜欢@ 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;