简体   繁体   English

如何将每个“一个”的一对多联接查询的结果减少到一个signle对象中?

[英]How to reduce the results from one-to-many join query into a signle object for each “one”?

Suppose I have 2 tables: 假设我有2张桌子:

Applicants:
- id
- full_name
- address

Educations:
- id
- applicant_id
- institute
- address

After I did an inner join, I want to loop through the data on a template. 在进行内部联接之后,我想遍历模板上的数据。 But first I want to convert all educational records for an applicant into an array and attach it to the applicant record. 但是首先,我想将申请人的所有教育记录转换成数组并将其附加到申请人记录中。

applicant_a:
- id
- full_name
- address
- educations: [ OBJECTS HERE ]

What's the way to do so? 这样做的方式是什么? Can I do it on the database side via SQL? 我可以通过SQL在数据库端执行此操作吗? Or do I have to do it on PHP side? 还是我必须在PHP方面做到这一点?

This is a simple draft of how I would do it in your case. 这是我将如何处理您的情况的简单草案。
I'm not saying this is the best or even the only way to do it. 我并不是说这是最好甚至唯一的方法。
This specific is not tested, though I used that logic often before. 尽管我以前经常使用该逻辑,但是未测试此特定逻辑。
Note, that this is only about the logic here.... but this should give you what you want! 请注意,这仅与此处的逻辑有关。...但这应该可以为您提供想要的!

$applicants = array();
$old_applicant_id=null;

while ($row=$db->fetch()) {

    // new applicant
    if($row['applicant_id']!=$old_applicant_id) {
        // save the education to the old one - if there is one
        if(isset($applicant)) {
            $applicant['education'] = $educations;
            $applicants[] = $applicant;
        }
        // then (and in first round)
        $applicant = array();
        $applicant['fullName'] = $row['fullName'];  
        // repeat for other values of applicant

        $educations = array(); // initialize educations
        $education = array();
        $education['id'] = $row['edu_id'];
        // repeat for institute, etc
        $educations[] = $education;
    } else {
        // already existing applicant, so only add education
        $education = array();
        $education['id'] = $row['edu_id'];
        // repeat for institute, etc
        $educations[] = $education;
    }
    // set old applicant
    $old_applicant_id = $row['applicant_id'];
}
// finally you have to save the last one to the array
$applicant['education'] = $educations;
$applicants[] = $applicant;

Another way would be to have two seperate queries and merge them in two loops. 另一种方法是拥有两个单独的查询,然后将它们合并为两个循环。

This question of mine was related. 我的这个问题是有关的。 I was asking about the spead of the two versions. 我在问两个版本的区别。 Might be interesting. 可能会很有趣。

MySQL does not return arrays, so this kind of thing is usually best done in client code (in this case PHP). MySQL不返回数组,因此通常最好在客户端代码(在这种情况下为PHP)中完成这种事情。

But if you are just going to concatenate the educations into a string of some sort you may want to look into the GROUP_CONCAT aggregate function. 但是,如果您只是要将教育内容连接成某种形式的字符串,则可能需要研究GROUP_CONCAT聚合函数。

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

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