简体   繁体   English

从多对多表中选择所有数据的最有效方法是什么?

[英]What is the most effective way to select all data from many-to-many table?

I designed many to many table below:我设计了下面的多对多表:

activity
----------
id
name
activity_student
----------
id
activity_id
student_id
student
----------
id
name

Each students can participate lots of activities, and each activities can have many participants.每个学生可以参加很多活动,每个活动可以有很多参与者。

And I want to select from activity, and at the same time, I want to collect the participants as array.我想从活动中进行选择,同时我想将参与者收集为数组。

The final data I want to make is like:我想要制作的最终数据是这样的:

[
  id => 1,
  name => football club activity,
  participants =>
    [
      [
        id => 1,
        name => example student,
        class => 3
      ],
      [
        id => 3,
        name => example student2,
        class => 5
      ]
    ]
]

I tried to select activity.* and group_concat for student_id.我尝试为 student_id 选择 activity.* 和 group_concat。 And then I retrieved student's data using foreach statement.然后我使用 foreach 语句检索学生的数据。

But I think it is not the best practice, since the query time became longer than 10 second with 10,000+ rows.但我认为这不是最佳实践,因为查询时间超过 10 秒,并且有 10,000 多行。

What is the best practice?最佳做法是什么?

  • I am using CI4, mysql database with InnoDB engine.我正在使用带有 InnoDB 引擎的 CI4、mysql 数据库。

It is almost always more efficient to do a complex task in SQL instead of dragging lots of data back to the client and then processing the data.在 SQL 中执行复杂任务几乎总是更有效,而不是将大量数据拖回客户端然后处理数据。 Especially in your case where you would be going back and forth to the database.特别是在您要来回访问数据库的情况下。

Read about JOIN .阅读关于JOIN

SELECT  a.name AS ActivityName,
        s.name AS StudentName,
        ...
    FROM activity AS a
    JOIN activity_student AS map  USING(activity_id)
    JOIN student AS s  USING(student_id)
    WHERE ...

You get back a table-like structure that has ActivityName, StudentName, etc. In the WHERE you can filter down to one activity or whatever.您会返回一个类似表格的结构,其中包含 ActivityName、StudentName 等。在WHERE您可以过滤到一个活动或其他任何内容。

Tips on an efficient schema for the mapping: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table关于映射的有效模式的提示: http : //mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

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

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