MySQL 选择行(如果在另一行中指定)


MySQL select row if it's specified in another row

我有一个包含多行的表,其中有些行是另一行的"子项"。

该表如下所示:

ID, 名称, 父项, 蛞蝓

示例数据:

1, Jack, NULL, jack 
2, John, NULL, john 
3, Mike, jack, mike

查询应返回 jack,因为它是 Mike 的父级。

所以我想返回在其他行中指定为"父项"的行。我真的是MySQL的新手,我不知道该怎么做。

不幸的是,我在谷歌上也没有走运,因为我不确定如何确切地问。

谢谢!

如果需要包含子项的行:

select distinct p.*
from table p join
     table c
     on p.name = c.parent;

或者,类似地:

select p.*
from table p
where exists (select 1 from table c where c.parent = p.name);

注意:table的意思是放在你的桌子上。

你需要这样的东西:

SELECT * FROM table_name AS t1 WHERE 
    (SELECT COUNT(*) FORM table_name AS t2 WHERE t2.parent = t1.name) > 0

SELECT t1.* FROM table_name AS t1 
    LEFT JOIN table_name AS t2 ON t2.parent = t1.name
    GROUP BY t1.id
select parent_person.* 
from person
    inner join person as parent_person on parent_person.name = person.parent