0

假设我有一个包含两个表的数据库:people其中包含每个人的 id 和他/她的出生年份,parents其中包含(parent_id, child_id)表示人与人之间相对关系的对。为了使解释更容易,我们假设每个人有 0 个孩子或 1 个孩子。这是数据库中数据的示例(作为一组 SQL 语句在 MySQL 上创建它):

CREATE TABLE people (
    id  INTEGER NOT NULL AUTO_INCREMENT,
    birth_year  INTEGER NOT NULL,
    CONSTRAINT PRIMARY KEY(id)
);

CREATE TABLE parents (
    parent_id   INTEGER NOT NULL,
    child_id    INTEGER NOT NULL,
    CONSTRAINT PRIMARY KEY(parent_id,child_id)
);

-- Not creating FOREIGN KEYS, because it's just an example

INSERT INTO people (id, birth_year) VALUES (1, 1937);
INSERT INTO people (id, birth_year) VALUES (2, 1943);
INSERT INTO people (id, birth_year) VALUES (3, 1974);
INSERT INTO people (id, birth_year) VALUES (4, 2001);
INSERT INTO people (id, birth_year) VALUES (5, 2020);

INSERT INTO parents (parent_id, child_id) VALUES (1, 4);
INSERT INTO parents (parent_id, child_id) VALUES (3, 5);

结果:

人表

父母表

现在我想创建一个查询来检索这个id人的年龄,他的孩子出生于父母的最早年龄(例如,如果我出生于 1234 年,我的孩子出生于 1300 年,那么我的年龄孩子出生了1300 - 1234 = 66,我想找一个比其他人更早得到孩子的人)。

我已经为此提出了一些查询,但它们中的每一个都没有工作或有重复或两者兼而有之。我最喜欢的是

SELECT id AS pid, -- Parent id
(SELECT child_id FROM parents WHERE parent_id=pid) AS cid -- Child id
FROM people WHERE
EXISTS(SELECT cid) -- Only selecting parents who have children (not sure this part is correct)
ORDER BY (birth_year - (SELECT birth_year FROM people WHERE id=cid)) ASC -- Order by age when they got their child
LIMIT 1;

但是这个在 MySQL 中失败并出现错误:

ERROR 1054 (42S22) at line 24: Unknown column 'cid' in 'field list'

如何修复错误?我担心的另一件事是,结果,我不仅会选择父母的 id,还会选择他/她的一个孩子的 id。有可能避免吗?可能有更好的方法来选择我正在寻找的数据?

4

1 回答 1

1

您可以使用连接来获取年龄:

select c.*, (p.birth_year - c.birth_year) as parent_age 
from parents pa join
     people p
     on pa.parent_id = p.id join
     people c
     on pa.child_id = pc.id;

要获得最小值的所有行,请使用窗口函数:

select x.*
from (select c.*, (p.birth_year - c.birth_year) as parent_age,
             min(p.birth_year - c.birth_year) over () as min_age
      from parents pa join
           people p
           on pa.parent_id = p.id join
           people c
           on pa.child_id = pc.id
     ) x
where parent_age = min_age;
于 2020-09-29T15:46:21.330 回答