SQL 对 select 所有死者的声明
SQL statement to select all dead people
我有桌子:
- 城市:
zip, name,...
- 人:
id, city_zip(refers to city.zip), born_time, dead_time
我需要 select 有关城市的所有人员都已死亡的城市的数据:born_time NOT NULL AND dead_time < NOW()
因为如果我们没有信息,我们不会假设某人已经死亡。
您可以使用 not exists
:
select c.*
from city c
where not exists (
select 1
from people p1
where p1.city_zip = c.zip and (dead_time is null or dead_time > now())
)
这也会 return 根本没有人的城市。如果这是您想避免的事情,那么另一种选择是聚合:
select c.*
from city c
inner join people p on p.city_zip = c.zip
group by c.zip
having max(case when dead_time is null or dead_time > now() then 1 else 0 end) = 0
select c.* ... from city c ... group by c.zip
是有效的标准SQL(假设zip
是tablecity
的主键)。但是,并非所有数据库都支持它,在这种情况下,您需要在 select
和 group by
子句中枚举所需的列。
我有桌子:
- 城市:
zip, name,...
- 人:
id, city_zip(refers to city.zip), born_time, dead_time
我需要 select 有关城市的所有人员都已死亡的城市的数据:born_time NOT NULL AND dead_time < NOW()
因为如果我们没有信息,我们不会假设某人已经死亡。
您可以使用 not exists
:
select c.*
from city c
where not exists (
select 1
from people p1
where p1.city_zip = c.zip and (dead_time is null or dead_time > now())
)
这也会 return 根本没有人的城市。如果这是您想避免的事情,那么另一种选择是聚合:
select c.*
from city c
inner join people p on p.city_zip = c.zip
group by c.zip
having max(case when dead_time is null or dead_time > now() then 1 else 0 end) = 0
select c.* ... from city c ... group by c.zip
是有效的标准SQL(假设zip
是tablecity
的主键)。但是,并非所有数据库都支持它,在这种情况下,您需要在 select
和 group by
子句中枚举所需的列。