mysql - 如何从已知外键列的表中进行选择
问题描述
表 foo_bar
id | name | parent(foreign key)
------------------
1 | foo | null
2 | bar | 1
3 | sql | 1
如果外键列已知,如何选择行?例如,我想选择父名称为 'foo' 的所有行,它应该输出 bar 和 sql 行
解决方案
你需要一个自我加入:
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')
推荐阅读
- java - NPE in Timer.schedule in Spring
- scala - 使用 akka 流从服务器下载二进制数据
- php - 按日期分组并显示 X(column) 的值,这取决于该日期的最小时间和该日期的最大时间在 1 行中
- python - 使用 Seaborn 绘图时如何根据年份展开绘图的日期轴?
- ios - UILabel 文本上的渐变描边
- oracle - 无法在 Spring Cloud Data Flow 中为 Oracle 添加 JDBC 驱动程序
- javascript - 使用 Redux 操作处理数据时出错
- laravel - Laravel - 如何使用 package.json 版本属性作为 process.env.APP_VERSION?
- javascript - 合并连续的 observables
- python - Keras 中最后一层的特征提取