首页 > 解决方案 > 如何从已知外键列的表中进行选择

问题描述

表 foo_bar

id | name | parent(foreign key)
------------------
1  | foo  | null
2  | bar  | 1
3  | sql  | 1

如果外键列已知,如何选择行?例如,我想选择父名称为 'foo' 的所有行,它应该输出 bar 和 sql 行

标签: mysqlsql

解决方案


你需要一个自我加入:

select f1.*
from foo_bar f1 inner join foo_bar f2
on f1.parent = f2.id
where f2.name = 'foo'

或者您可以先获取父级的 id 并在 WHERE 子句中使用它:

select * from foo_bar
where parent = (select id from foo_bar where name = 'foo')

推荐阅读