2014-10-28 42 views
0

我有一个父子关系表的id,这是多对多关系表和用户id存储在用户表中,表格的基本格式在这里:mysql:在父亲儿子关系表中查找第一个父亲的单个查询

.......................... | father_id | son_id | ........................... | A | B | .......................... | B | C | .......................... | C | D | .......................... | D | E |

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

+0

MySQL是不是好来处理递归查询,但如果关系的深度已知,那么使用单个查询您可以旅行来回。另一方面,您可以使用PHP递归函数轻松完成工作。 – 2014-10-28 06:51:24

+0

感谢您的建议,所以它不可能与MySQL – Shivam 2014-10-30 07:20:19

+0

“最伟大的祖父”并不意味着什么。如果你想*伟大的祖父*,那么“关系的深度是已知的”,并且查询很简单。 (否则请参阅[this](https://dba.stackexchange.com/questions/7147/find-highest-level-of-a-hierarchical-field-with-vs-without-ctes/7161#7161)。)但是“任何一个儿子”都不清楚。使用小而明确的句子和短语。不要满足于某些不清楚的事情;继续编辑。你想要每个父亲是曾祖父的父亲吗? – philipxy 2014-12-09 07:29:31

回答

0

你的问题还不清楚,但如果你想每一个爸爸谁是曾祖父的father_id:

你的表行,其中“人[father_id]是的人[son_id]之父”。以is_father_of(father_id,son_id)的形式简写。请注意,速记就像一个SQL表格声明。别名fs,gs,ggs到您的原始表is_father_of。你要行(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