SQL语句选择所有死者

问题描述

我有桌子:

  • 城市: zip,name,...
  • 人们: id,city_zip(refers to city.zip),born_time,dead_time

我需要选择有关该城市所有人员死亡的城市的数据: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())
)

这也将返回根本没有人的城市。如果您想避免这种情况,那么另一个选择是聚合:

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是表city的主键)。但是,所有数据库都不支持它。在这种情况下,您将需要枚举selectgroup by子句中想要的列。