我在 MySQL 中有一张表来存储家庭成员。看起来像这样
CREATE TABLE housembers (
id int,
houseid int,
housemberid int,
year_of_birth int
);
它与家庭表具有多对一关联。
示例数据可能是:
1, 1, 1, 1980
2, 1, 2, 1977
3, 2, 1, 1969
4, 3, 1, 1950
Etc...
查找所有成员都超过特定年龄的所有家庭的最有效查询是什么?
谢谢!
最佳答案
一种方法是聚合:
select houseid
from housemembers
group by houseid
having max(year_of_birth) < date_sub(curdate(), interval @age years);
另一种方法使用not in
/not exists
但需要去重:
select distinct houseid
from housemembers hm
where not exists (select 1
from housemembers hm2
where hm2.houseid = hm.houseid and
year_of_birth >= date_sub(curdate(), interval @age years)
);
这可能并不比第一个版本更有效。但是,如果您有一个 houses
表(每个 houseid
一行)和正确的索引,这应该会更快:
select houseid
from houses h
where not exists (select 1
from housemembers hm2
where hm2.houseid = h.houseid and
year_of_birth >= date_sub(curdate(), interval @age years)
);
关于mysql - SQL查询以查找每个人都超过特定年龄的所有房屋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192545/