2016-11-25 90 views
0

我有这样的顺序表,我想从这个表中获取数据,其中每一行取决于其他获得我需要的信息。继承格式使用PHP Mysql数据

  ID USERNAME     REFFERAL   USER1           2.   USER2。             user3。             user4。           5.   User5。          

$sql = mysqli_query($server, “select refferal from profile where id=‘5’”); 
$row1 = mysqli_fetch_assoc($sql); 
$ref1 = $row[‘refferal’]; 

$sql2 = mysqli_query($server, “select refferal from profile where id=‘$ref1’”); 
$row2= mysqli_fetch_assoc($sql2); 
$ref2 = $row2[‘refferal’]; 

$sql3 = mysqli_query($server, “select refferal from profile where id=‘$ref2’”); 
$row3= mysqli_fetch_assoc($sql3); 
$ref3 = $row3[‘refferal’]; 

$sql4 = mysqli_query($server, “select refferal from profile where id=‘$ref3’”); 
$row4= mysqli_fetch_assoc($sql4); 
$ref4 = $row4[‘refferal’]; 

我希望得到的USER4的所有用户名,用户3,用户2,用户1在一个查询,如果可能的。这是我到目前为止已经试过,但我不不认为它是非常有效的。

+0

这是自联接查询 – Drew

+0

我会很高兴如果有人向我指出** referral **拼写有两个“r”,特别是如果我正在起草原始的HTTP_REFERER http标头字段https://en.wikipedia.org/wiki/HTTP_referer – WEBjuju

回答

0

加入一个表格时,我发现左连接最容易理解的情况下,右侧没有数据(左侧仍然显示,右侧将为空......在没有推荐的情况下)。

该查询将用户5的原始输入和通过左连接的自连接进行3次以查找用户的引用链。

select 
    p1.username ref1, p2.username ref2, p3.username ref3, p4.username ref4 
from 
    profile p1 left join 
    profile p2 on p1.refferal = p2.id left join 
    profile p3 on p2.refferal = p3.id left join 
    profile p4 on p3.refferal = p4.id 
where 
    p1.id = 5; 

行的输出将是四个字段名称REF1,REF2,REF3和REF4其中REF1是id为原始用户= 5

+0

你为我节省了一些时间 – joshua