sql - Joining/Querying Self-Referential "Grandchildren" Tables
问题描述
Say I have a table as following:
countries
| ID | Name | Population | Continent |
Countries is self-referential, and has an association table:
alliances
| country_id | ally_id |
I understand that I need to use the 'AS' keyword to join the table, say, as c1, c2, etc. But I can't quite wrap my head around how to go about this for grandchildren, great grandchildren, etc.
How would I write SQL, for example, to get the countries where they have an ally' who's ally's population is greater than 50 000 000?
I'm generating this SQL based off of models defined in code, so need to be able to support this kind of behaviour up to a user-defined depth.
Thanks!
解决方案
您的示例的查询是
SELECT c1.name
FROM countries AS c1
JOIN alliances AS a ON c1.id = a.country_id
JOIN countries AS c2 ON a.ally_id = c2.id
WHERE c2.population > 50000000;
如果这是一个家庭作业问题(看起来像一个),那么您已经找到了为您做这件事的傻瓜。
推荐阅读
- azure - 无法使用 terraform 或 azcli 在 azure 中将私有 IP 添加到 Appgateway
- ios - xcode 11 中的 NumberFormatter
- android - 与内置游戏中统一 3d android 中的纹理相关的错误
- ios - 更新到最新的 Xcode 后找不到 Video.mp4
- sql - SQL 查询之争 - 如何计算每个用户每天的用户登录次数
- python - 如何从字节数组在python中生成RGB图像?
- module - 通过文件夹和子文件夹运行的模块
- php - 使用 index.php/en 之类的语言从 codeigniter 中删除 index.php
- java - 如何从 application.yaml 文件中获取值?
- sql - Oracle 生成多条记录