簡體   English   中英

SQL:為嵌套 SELECT 創建全局別名以在另一個嵌套 SELECT 中使用

[英]SQL: create global alias for nested SELECT to be used in another nested SELECT

假設我有一個包含兩個表的數據庫: people包含每個人的 id 和他/她的出生年份,以及包含(parent_id, child_id)對的parents ,以表示人與人之間的相對關系。 為了使解釋更容易,讓我們假設每個人有 0 個孩子或 1 個孩子。 以下是數據庫中數據的示例(作為在 MySQL 上創建它的一組 SQL 語句):

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。 有可能避免嗎? 可能有更好的方法來選擇我正在尋找的數據?

您可以使用連接獲取年齡:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM