PHPとmysqlから始まる人物として、あなたが望むものを得るための完全なコード例がここにあります。ここには魔法のSQLはありませんが、PHPループ(カウントリミッター付き)は、DBに接続の親を尋ねる繰り返しです。
<?php
/* setup your database information */
$host = 'localhost';
$user = 'db_username';
$pass = 'db_password';
$db = 'db_name';
$link= mysqli_connect($host,$user,$pass,$db); // connect to the database
if (mysqli_connect_errno()) { // if fail connection... exit.
die(mysqli_connect_error());
}
/* the function to locate the first user in the chain of connections */
function find_first_user($link,$first,$last,$max_count=10){
$cnt=0; // local counter as prtection to never go over the $max_count
$parent=0;
$tbl='myTableName';
// find info about the person in question via the first & last name
$q="select parentUserId from $tbl where firstName='" . mysqli_real_escape_string($link, $first) .
"' and lastName='" . mysqli_real_escape_string($link, $last) . "'";
if($res=mysqli_query($link, $q)){
list($parent)=mysqli_fetch_row($res);
}
// if we found a parentId, repeat looking in the chain of connections
while($parent && ++$cnt<$max_count){
$q="select parentUserId,firstName,lastName from $tbl where userId=".intval($parent);
if($res=mysqli_query($link, $q)){
list($parent,$first,$last)=mysqli_fetch_row($res);
}
}
return "$first $last";
}
// example usage
print find_first_user($link,'Stephen','Lopez') . "\n";
?>
知っていますか?そうであれば、一定数の結合を行い、答えを得ることができます。これ以外にも、あなたは再帰的クエリを求めていると思います。はい、これもPHPから処理することができますが、私はそれが一番良い方法だとは思いません。 –
これに続く - http://stackoverflow.com/questions/31168675/how-to-mak-a-recursive-self-join-in-mysqlまたはthis - http://stackoverflow.com/questions/8104187/hierarchical- queries-in-mysql –