简体   繁体   中英

SQL multiple tables grouping students

Trying to group students based on these which groups they are in. I'm trying to dispaly the result in some sort of object/JSON so that I could apply some sorting algorithims in JS later. Not sure how to add the WHERE statement or Join statement?

$link = mysqli_init();
$success = mysqli_real_connect( $link, $host, $user, $password, $db, $port);
$query = mysqli_query($link, "SELECT s_id, group_id, name FROM Group, Student");

    $table = array(); 
    while($row = mysqli_fetch_assoc($query)) 
    { 
    $table = $row;
     echo json_encode($table);
     }


I want result something like 
`
[{'Group': 1, 'name': 'john', 'ID': 101},
{'Group': 1, 'name': 'mike', 'ID': 103},
{'Group': 2, 'name': 'alice', 'ID': 102}, 
{'Group': 2, 'name': 'rachel', 'ID': 104},]`







the "Student" table

    s_id     class_id   name
    101         1         john
    103         1         mike
    102         1         alice
    104         1         rachel

the "Group" table


    class_id   s_id    group_id
    1          101         1
    1          102         2
    1          103         1
    1          104         2

Change your SQL with:

SELECT G.group_id AS `Group`, 
       S.name, 
       S.s_id AS ID
FROM Student S
JOIN `Group` G ON S.s_id = G.s_id
ORDER BY G.group_id, S.s_id

It is an INNER JOIN between the 2 tables on the Student id column, and we choose the columns that we want to show, and order the result as we want.

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