SQL查询查找所有人都超过一定年龄的所有家庭

时间:2016-03-24 03:00:18

标签: mysql sql

我在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...

查找所有成员超过一定年龄的所有家庭的最有效查询是什么?

谢谢!

1 个答案:

答案 0 :(得分:4)

一种方法是聚合:

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)
                 );