如何在单个查询中从2个表中查询这些行?

问题描述 投票:0回答:1
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

如何在单个查询中基于表2(student_id 1)中的student_id从表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();
    }
}
mysql sql prepared-statement
1个回答
0
投票

您可以使用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();

0
投票

我相信您可以通过以下查询来实现:

SELECT T1.STUDENT_ID,T1.NAME从TABLE_1 T1,TABLE_2 T2T1.STUDENT_ID = T2.VOTE_FORAND T2.STUDENT_ID =?

而且您只需为表2注入STUDENT_ID。

© www.soinside.com 2019 - 2024. All rights reserved.