使用外键,如何打印出外键所引用的主键的列?

时间:2019-05-09 20:22:14

标签: php mysql foreign-keys relationship

我有两个表,一个类表和一个教授表。使用mySQL,

describe class
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| class       | varchar(225) | NO   |     | NULL    |                |
| description | varchar(225) | NO   |     | NULL    |                |
| prof_id     | int(11)      | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

prof_id是外键,另一个是表

describe professor
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(255) | NO   |     | NULL    |                |
| office   | varchar(20)  | NO   |     | NULL    |                |
| phone    | varchar(50)  | NO   |     | NULL    |                |
| email    | varchar(50)  | NO   |     | NULL    |                |
| username | varchar(100) | NO   |     | NULL    |                |
| password | varchar(100) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

id是class.prof_id所引用的主键。我要使用网络应用程序,并且要根据给定的prof_id打印出Professor.name。 (即:如果一位名叫John Doe id的教授= 1,并且如果prof_id中有1,我希望打印 John Doe 。这是我的php代码:

<?php
require_once('connect.php');
session_start();

$resultQuery = mysqli_query($mysqli, "SELECT * FROM professor");
?>

------SKIPPING OVER USELESS HTML/CSS-------

 <table>
    <tr>
        <u><th>Name</th> <th>Class</th> <th>Description</th> <th>Professor</th> <th>Update</th></u>
    </tr>
    <?php
    while($user_data = mysqli_fetch_array($resultQuery))
    {
        echo "<tr>";
        echo "<td>".$user_data['class']."</td>";
        echo "<td>".$user_data['description']."</td>";
        echo "<td>".$user_data['prof_id']."</td>";
        echo "<td><button><a href='editClasses.php?id=$user_data[id]'>Edit</a></button><button><a href='deleteClasses.php?id=$user_data[id]'>Delete</a></button></td></tr>";
    }
    ?>
</table>

1 个答案:

答案 0 :(得分:0)

您可以使用JOIN通过外键联接2个表。如果您想保留ID列的名称,则可以为其命名,例如SELECT professor.name AS prof_id。然后,您的prof_id列将保留实际名称而不是ID。

始终明确列出您的列始终是一个好主意。

$sql = "SELECT class, description, professor.name AS prof_id 
    FROM class 
    JOIN professor ON professor.id=class.prof_id";
$resultQuery = mysqli_query($mysqli, $sql);