我们假设有一个名为people的表,其中包含以下列:
我试图写一个查询来返回以下内容:
我对第4项子查询有困难。
我的问题是:
如何从子查询中的父查询引用person.person_parent_id?如果我能从外部查询中获取people.parent_person_id值并在内部查询中使用它,我觉得在下面的代码中,我会实现我的目标。
SELECT
people.person_id as 'Person ID',
people.name as 'Person Name',
people.parent_person_id as 'Parent ID',
(
SELECT
people.name
FROM
people
WHERE
people.parent_person_id = people.person_id;
) as 'Parent Name'
FROM
people;
我可能错了,我绝对心胸开阔。请分享你的想法,并帮助这位善良的灵魂继续他的追求。
答案 0 :(得分:3)
你很亲密。你只需要适当的表别名:
SELECT p.person_id as PersonID,
p.name as PersonName,
p.parent_person_id as ParentID,
(SELECT parent.name
FROM people parent
WHERE p.parent_person_id = parent.person_id;
) as ParentName
FROM people p;
注意:
LEFT JOIN
,但相关子查询也是一种非常合理的方法。people.parent_person_id = people.person_id
中,people
指的是内部from
。您需要表别名来区分people
的内部和外部引用。答案 1 :(得分:1)
只需为每个表创建一个别名
SELECT
p1.person_id as 'Person ID',
p1.name as 'Person Name',
p1.parent_person_id as 'Parent ID',
(
SELECT
p2.name
FROM
people as p2
WHERE
p2.parent_person_id = p1.person_id;
) as 'Parent Name'
FROM
people as p1;
答案 2 :(得分:1)
为什么不使用连接?
SELECT
p1.person_id as 'Person ID',
p1.name as 'Person Name',
p1.parent_person_id as 'Parent ID',
p2.name as 'Parent name'
FROM people p1
LEFT JOIN people p2 ON p1.parent_person_id = p2.person_id;