gpt4 book ai didi

mysql:通过父子关系表中的单个查询查找第一个父亲

转载 作者:行者123 更新时间:2023-11-29 23:30:37 26 4
gpt4 key购买 nike

我有一个父子id的关系表,这是多对多的关系表,用户的id存储在用户表中,表的基本格式如下:

........................
|父亲 ID |儿子ID |
……………………
|一个 |乙|
……………………
|乙| C |
……………………
| C | d |
……………………
| d |电子|

现在我必须找到任何一个儿子的最伟大祖父,我可以通过单个 MySQL 查询来实现这一目标还是必须使用 PHP 循环?

最佳答案

你的问题不清楚,但如果你想要每个曾祖父的父亲的father_id:

您的表格包含“person [father_id] 是 person [son_id] 的父亲”的行。将其简写为 is_father_of(father_id,son_id)。请注意,简写类似于 SQL 表声明。为原始表 is_father_of 指定别名 fs,gs,ggs。您想要行 (ggs.is_father_id) 位于

    is_father_of(fs.father_id,fs.son_id)
and is_father_of(gs.father_id,fs.father_id)
and is_father_of(ggs.father_id,gs.father_id)

这是

select gg.is_father_id
from is_father_of fs
join is_father_of gs on gs.son_id = fs.father_id
join is_father_of ggs on ggs.son_id = gs.father_id

关于mysql:通过父子关系表中的单个查询查找第一个父亲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26602039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com