gpt4 book ai didi

mysql - 比较 SQL 中的聚合值

转载 作者:可可西里 更新时间:2023-11-01 08:09:00 24 4
gpt4 key购买 nike

假设我有 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 个查询。

以下查询为我提供了车库的总 parking 位:

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;

但我想写一个Single 查询来比较这两个 SQL 并打印“车库已满”或“车库未满”。我该怎么做?

最佳答案

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

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;

关于mysql - 比较 SQL 中的聚合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51771579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com