如何在单个查询中查询 2 个表中的行?

How to query rows from 2 tables in a single query?

TABLE 1
student_id | name
-----------------
1          | A
2          | B
3          | C
4          | D

TABLE 2
vote_id   | student_id | vote_for
------------------------------
1          | 1          | 2
2          | 1          | 3
3          | 2          | 1
4          | 1          | 4

如何在单个查询中根据 TABLE 2 (student_id 1) 中的 student_idTABLE 1 (学生姓名 B C D) 获取记录?我设法做到了,但是在如下多个查询中:

$students = array();
$query = "SELECT vote_for FROM table2 WHERE student_id=?";          
$stmt = $this->con->prepare($query);
$stmt->bind_param("i",$student_id);
$stmt->execute();
$stmt->bind_result($vote_for);
$votes = array();
while($stmt->fetch()){
    $votes[] = $vote_for;
}
$stmt->close();
if (!empty($votes)) {
    $query = "SELECT name FROM table1 WHERE student_id=?";
    foreach ($votes as $vote) {
        $stmt = $this->con->prepare($query);
        $stmt->bind_param("i",$vote);
        $stmt->execute();
        $stmt->bind_result($name);
        while($stmt->fetch()){
            $temp = array(); 
            $temp['name'] = $name; 
            $students[] = $temp;
        }
        $stmt->close();
    }
}

您可以使用 JOIN 查询来获取给定 student_id 投票给学生的姓名。例如:

SELECT s.name AS voted_for
FROM table2 v
JOIN table1 s ON s.student_id = v.vote_for
WHERE v.student_id = 1

Demo on dbfiddle

在PHP中:

$students = array();
$query = "SELECT s.name AS voted_for
    FROM table2 v
    JOIN table1 s ON s.student_id = v.vote_for
    WHERE v.student_id = ?";          
$stmt = $this->con->prepare($query);
$stmt->bind_param("i",$student_id);
$stmt->execute();
$stmt->bind_result($name);
while($stmt->fetch()) {
    $students[] = array('name' => $name);
}
$stmt->close();

我相信你可以通过以下查询实现它:

SELECT T1.STUDENT_ID, T1.NAME 
FROM TABLE_1 T1, TABLE_2 T2
WHERE T1.STUDENT_ID = T2.VOTE_FOR
AND T2.STUDENT_ID = ?

您只需为 Table 注入 STUDENT_ID 2。如有必要,您可以删除 T1.STUDENT_ID。