开发者

How do you replace id numbers with names since the columns aren't joined directly? (PHP/MySQL)

开发者 https://www.devze.com 2023-03-28 01:21 出处:网络
Let\'s say you have a database with two tables named \"clients\" and \"referrals\". TABLE clients has two columns: \"id\" and \"name\".

Let's say you have a database with two tables named "clients" and "referrals".

TABLE clients has two columns: "id" and "name".

TABLE referrals also has two columns: "id" and "referred_by"

Both "id" columns are PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL

TABLE clients has three rows:

1 | Jack  
2 | Frank  
3 | Hank  

TABLE referrals also has three rows:

1 | 0  
2 | 1  
3 | 2  

Meaning, Jack is client 1 and was referred by no one; Frank is client 2 and was referred by Jack; Hank is client 3 referred by Frank.

The SELECT command I used to display the meaning above was:

mysql_query("SELECT clients.id, clients.name, referrals.referred_by FROM clients INNER JOIN referrals ON clients.id=referrals.id");

while ($row = mysql_fetch_array($result))
{
    echo $row['id'] . " " . $row['name'] . " " . $row['referred_by'] . "<br>";
}

Which outputs:

1 Jack 0  
2 Frank 1  
3 Hank 2  

Now the real question is:

How should I modify the code so that it outputs the name of the referrer instead of their id?

Meaning, it should look like this:开发者_如何学编程

1 Jack  
2 Frank Jack  
3 Hank Frank

Thanks in advance ~

Edit: Make sure to mention how I should update the array as I'm lost on how I should update that whole echo line.


You're almost there - you just need to join back to the clients table a 2nd time to get the referrer name:

mysql_query("SELECT clients.id, clients.name, rclients.name as referred_by
FROM clients 
INNER JOIN referrals ON clients.id=referrals.id
LEFT JOIN clients as rclients ON referrals.referred_by = rclients.id");

while ($row = mysql_fetch_array($result))
{
    echo $row['id'] . " " . $row['name'] . " " . $row['referred_by'] . "<br>";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消