简体   繁体   English

如何从表 1 中查询单行和从表 2 中查询多行?

[英]How to query single row from Table 1 and multiple rows from Table 2?

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

TABLE 2
photo_id   | student_id | path
------------------------------
1          | 1          | /path/to/folder/apple.jpg
2          | 1          | /path/to/folder/orange.jpg
3          | 2          | /path/to/folder/cantaloupe.jpg
4          | 1          | /path/to/folder/lemon.jpg

public function studentPhotos($student_id) {
    $query = "SELECT table1.name,table2.path as photos FROM table1 INNER JOIN table2 ON table1.student_id = table2.student_id WHERE table1.student_id=?";
    $stmt = $this->con->prepare($query);
    $stmt->bind_param("i",$student_id);
    $stmt->execute();
    $stmt->bind_result($name,$photos);
    $student = array();
    while($stmt->fetch()){
        $temp = array(); 
        $temp['name'] = $name;
        $temp['photos'] = $photos;
        $student[] = $temp;
    }
    $stmt->close();
    return $student; 
}

Result: [{A,/path/to/folder/apple.jpg},{A,/path/to/folder/orange.jpg},{A,/path/to/folder/lemon.jpg}]结果:[{A,/path/to/folder/apple.jpg},{A,/path/to/folder/orange.jpg},{A,/path/to/folder/lemon.jpg}]

Desired Result {A,/path/to/folder/apple.jpg,/path/to/folder/orange.jpg,/path/to/folder/lemon.jpg}期望的结果 {A,/path/to/folder/apple.jpg,/path/to/folder/orange.jpg,/path/to/folder/lemon.jpg}

Of course I can change it using PHP, but I'm talking hundreds of photos for every student.当然,我可以使用 PHP 更改它,但我说的是每个学生都有数百张照片。 So all student's attributes will be repetitive for as many as the photos in the result array.因此,对于结果数组中的照片,所有学生的属性都是重复的。

Is there a better way in query?有没有更好的查询方式?

Do you want to group concatenate here:你想在这里分组连接:

SELECT
    t1.name,
    COALESCE(GROUP_CONCAT(t2.path), 'NA') AS paths
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.student_id = t2.student_id
WHERE
    t1.student_id = ?;

You can use group_concat method.您可以使用group_concat方法。 It will give you comma separated values for the column specified.它将为您提供指定列的逗号分隔值。

Below is the query:以下是查询:

SELECT table1.name, 
       Group_concat(table2.path) AS photos 
FROM   table1 
       INNER JOIN table2 
               ON table1.student_id = table2.student_id 
WHERE  table1.student_id =? 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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