sql多表分组学生

nbysray5  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(272)

试着根据学生所处的群体对他们进行分组。我正试图在某种object/json中显示结果,以便稍后在js中应用一些排序算法。不确定如何添加where语句或join语句?

$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
wlp8pajw

wlp8pajw1#

将sql更改为:

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

它是student id列上两个表之间的内部联接,我们选择要显示的列,并根据需要对结果排序。

相关问题