【问题标题】:SQL statement to select all dead peopleSQL语句选择所有死人
【发布时间】:2020-09-03 15:48:20
【问题描述】:

我有桌子:

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

我需要选择有关该城市所有人员死亡的城市的数据:born_time NOT NULL AND dead_time < NOW()

因为如果我们没有信息,我们不会假设某人已经死了。

【问题讨论】:

标签: sql datetime count subquery


【解决方案1】:

你可以使用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 子句中枚举所需的列。

【讨论】:

  • 城市里总是至少有一个人,哪一种说法不那么“苛刻”,即更快?
猜你喜欢
  • 2010-12-02
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2017-12-19
相关资源
最近更新 更多