简体   繁体   中英

MySQL PHP ID in one table and not another

| Fixture_ID | League_ID | Home_Team | Away_Team 
|          1 |         1 |         1 |         2 
|          2 |         1 |         2 |         3 
|          3 |         1 |         3 |         1 

| Result_ID | Fixture_ID | Home_Goals | Away_Goals 
|         1 |          1 |          2 |          0

| Team_ID | Team_Name   |
|       1 | Team A  
|       2 | Team B      
|       3 | Team C 

How do I join the tables to show only the fixtures that haven't had results inputed but output the actual team names (Team A v Team B) when showing the fixture (in a drop down list)?

The following code works for outputting all fixtures:

echo '<td> <select name ="fixture_id">';    

// TRY TO SHOW FIXTURES WITH NO RESULTS
$stmt = $pdo->prepare('SELECT  f.*, t1.Team_Name AS Home, t2.Team_Name AS Away
                        FROM Fixture        f
                        INNER JOIN Team     t1 ON f.Home_Team = t1.Team_ID
                        INNER JOIN Team     t2 ON f.Away_Team = t2.Team_ID');


$stmt->execute();
foreach ($stmt as $row) {
    echo '<option>' . $row['Home'] . ' v ' .  $row['Away'] . '</option>';
}  

?>  

Your SQL should look like this:

SELECT  f.*, t1.Team_Name AS Home, t2.Team_Name AS Away
FROM Fixture        f
INNER JOIN Team     t1 ON f.Home_Team = t1.Team_ID
INNER JOIN Team     t2 ON f.Away_Team = t2.Team_ID
LEFT JOIN Result    r ON f.Fixture_ID = r.Fixture_ID
WHERE r.id IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM