Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 从两个表中选择所有数据,按第一个表中的项目分组(基本SQL)_Mysql_Sql_Arrays_Json_Subquery - Fatal编程技术网

Mysql 从两个表中选择所有数据,按第一个表中的项目分组(基本SQL)

Mysql 从两个表中选择所有数据,按第一个表中的项目分组(基本SQL),mysql,sql,arrays,json,subquery,Mysql,Sql,Arrays,Json,Subquery,我有两张桌子,例如: 课程 | id | name | room | |----|------|------| | 0 | Math | 203 | | 1 | Art | 617 | | id | name | class | |----|---------|-------| | 0 | Charlie | 0 | | 1 | Bill | 0 | | 2 | Carly | 1 | 学生 | id | name | room | |

我有两张桌子,例如:

课程

| id | name | room |
|----|------|------|
| 0  | Math | 203  |
| 1  | Art  | 617  |
| id | name    | class |
|----|---------|-------|
| 0  | Charlie | 0     |
| 1  | Bill    | 0     |
| 2  | Carly   | 1     |
学生

| id | name | room |
|----|------|------|
| 0  | Math | 203  |
| 1  | Art  | 617  |
| id | name    | class |
|----|---------|-------|
| 0  | Charlie | 0     |
| 1  | Bill    | 0     |
| 2  | Carly   | 1     |
以下是我想要的输出:

[
  {
  "id": 0,
  "name": "Math",
  "room": 203,
  "students": [
     {
      "id": 0,
      "name": "Charlie"
     },
     {
      "id": 1,
      "name": "Bill"
     },
   ]
 },
 {
  "id": 1,
  "name": "Art",
  "room": 617,
  "students": [
     {
      "id": 2,
      "name": "Carly"
     },
   ]
 },
]
我尝试了
SELECT*FROM classes在课堂上加入学生。id=students.class
但这显然让我把所有的学生排成了一排,每排都有班级


很抱歉问了一个基本的问题,我只是不知道该用谷歌搜索什么。

如果你想让每门课有一行,所有对应的学生都在一个JSON数组中,你可以使用JSON聚合函数和一个相关的子查询:

select c.*,
    (
        select json_arrayagg(json_object('id', s.id, 'name', s.name))
        from students s
        where s.class = c.id
    ) as students
from classes c

你在这里使用PHP吗?是的,PHP。但在理想情况下,它会全部出现在查询中,对吗?理想情况下?我们对什么是“理想”有非常不同的想法!!!在这种情况下,什么对您最理想@Strawberry将加入表,并按照您的建议在应用程序代码中解析平面结果谢谢。这只是我需要的一个基本例子。实际上,“学生”表中还有其他列。有没有一种方法可以在不列出json_对象函数中的所有键值对的情况下做到这一点?理想情况下,我只想从两个表中获取所有值,但按我列出的方式进行格式化above@danthony:不幸的是,没有。在MySQL中,您需要枚举键/值对来创建json对象。