php - 在 MySQL 端或 PHP 端对 SQL 数据进行分组?

标签 php mysql

我在 MySQL 中有以下表:

team: id, name, [more stuff]
person: id, name, team, [more stuff]
entry: id, name, team, [more stuff]
registrations: id, event_id, team, status
registration_people: registration_id, person_id
registration_entries: registration_id, entry_id

我想查询数据库,并返回每个人和条目的详细信息;按注册分组。多年来我学会了尽可能多地使用 SQL。但是,我没有看到在单个查询中生成此内容而无需在 PHP 中进行大量工作的好方法。执行此操作的简单方法是[伪代码]:

$registrations = $model->get_registrations($event_id);
foreach ($registrations as $registration)
{
    $registration['people'] = $model->get_people_in_registration($registration['id']);
    $registration['entries'] = $model->get_entries_in_registration($registration['id']);
}
return $registrations;

此代码会多次往返服务器,因此不应使用。我的另一个想法是做类似的事情:

$registrations = $model->get_registrations($event_id);
$registration_entries = $model->get_registration_entries($event_id);
$registration_people = $model->get_registration_people($event_id);
foreach ($registrations as $r)
    $reg[$r['id']] = $r;
foreach ($registrations_entries as $e)
    $reg[$e['registration_id']]['entries'][] = $e;
foreach ($registrations_people as $p)
    $reg[$p['registration_id']]['people'][] = $p;
return $reg;

其中 get_registration_entries/get_registration_people 执行联接,并获取与 $event_id 中的注册关联的所有 registration_entries。然而,这似乎是我在 PHP 中进行连接;当我可以让 SQL 为我做这件事时。我只是偏执,还是我错过了什么?

最佳答案

“尽可能多地使用 SQL 进行操作”这一概念仅在减少从数据库读取的数据量或数据库往返次数时才有效。如果您无论如何都需要获取数据,那么将其分组到数据库中有何意义?在 PHP 中做到这一点要容易得多。

你应该这样做:

select r.registration_id, p.*
from registration_people rp, registrations r, person p
where /* your filter conditions on the "registration" table */
and rp.registration_id = r.id
and p.id = rp.person_id

(我想这与你的第二种方法几乎相同)

这样,您就可以从数据库中获取所有相关数据,不再需要更多数据。现在您可以在 PHP 中本地对结果进行分组。这种方法非常有效,因为您只需从数据库中获取所需的数据,并且不会对数据库进行不必要的往返。

关于php - 在 MySQL 端或 PHP 端对 SQL 数据进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/445481/

相关文章:

php - 将帖子从另一个数据库添加到 WP 数据库

php - 使用 PHP gd 时为 "Could not find/open font"

php - 使用 Cron 和 PHP API 以编程方式发布 Facebook 页面状态

PHP : How to merge child arrays?

javascript - 如何在php中获取确认框值

php - Doctrine,@oneToMany,但只有激活字段

php - 我们向用户提示的详细信息(通过 php 编码)未显示在 MySQL 数据库(本地主机)中

mysql - Mongodb 查找查询 "where"Billing Address is Equal to Delivery Address

mysql - Left Join ON LIKE 需要像 LIMIT 这样的东西

mysql - 计算数据类型 TIME 的十进制数