jsheffers
jsheffers

Reputation: 1622

How to reference another table with a consistent primary key across tables

I have two tables which both have a unique PID. I need to know how I should setup the primary/foreign keys so I can access fields from both tables in one SQL statement.

For example: With the following data structure i'd like to echo out the players name and photo but also echo out all their stats via PHP as well. I have successfully done this with just the player Stats, but I do not know how to get access to fields in another table.

Here is my database structure so far:

Players
-PID (Set as Primary Key)
-Name
-Height
-College
-Photo

Stats
-PID 
-Touchdowns
-Receptions

Current PHP Code:

$query="
SELECT * FROM Stats    
ORDER BY Stats.FantasyPoints DESC";

$res=mysql_query($query);
$num=mysql_numrows($res);
$i=0;

while($i< $num){
$Name = mysql_result($res, $i, "Name");
$FantasyPoints = mysql_result($res, $i, "FantasyPoints");

echo $Name . ': '. $FantasyPoints . "<br />";
$i++;
}

Upvotes: 0

Views: 229

Answers (1)

Dale
Dale

Reputation: 10469

$sql = "
SELECT p.*, s.*
FROM Players AS p
LEFT JOIN Stats AS s ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";

You could also use a JOIN rather than a LEFT JOIN which would limit the result to only players who have stats

Edited sql to produce result similar to your own sql.

======================================================

This is how I would go about it...

$query =
"
SELECT s.*, p.*
FROM Stats AS s
LEFT JOIN Players AS p ON p.PID = s.PID   
ORDER BY s.FantasyPoints DESC
";

$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
    echo "{$row['name']}: {$row['FantasyPoints']}<br />";
}

Upvotes: 2

Related Questions