Mysql加入1行多行 - group concat或php?

时间:2012-08-25 09:44:44

标签: php mysql group-concat

考虑以下示例:

+----------+--------+-------------+----------+
| Person_id| Person | Language_id | Language |
+----------+--------+-------------+----------+
| 1        | Bob    | 5           | English  |
| 1        | Bob    | 3           | Italiano |
| 1        | Bob    | 8           | Deutsch  |
+----------+--------+-------------+----------+

并且查询是(不那么重要,只是脚本以向您显示表结构):

SELECT pl.Person_id, Person, Language_id, Language FROM people as p
LEFT JOIN people_languages as pl ON p.Person_id = pl.Person_id 
LEFT JOIN languages as l ON pl.language_id = l.language_id
WHERE pl.Person = 1;

所以基本上,如果以这种方式构造表,最好是如上所示检索所有结果,然后创建一个php函数,用一个数组中的languages_id和语言创建一个Person Model,或者使用{{1}检索单行,然后将语言和languages_id分解为数组?

顺便说一下,无论我做什么,最后我都希望有一个人物模型如下:

group_concat

3 个答案:

答案 0 :(得分:2)

这是答案。你可以使用这两种方式,但在我看来,使用group concat要好得多。原因是这将提高性能以及减少PHP代码。如果你继续你给出的例子,你将不得不在php端做很多编码。有时在php端处理变得困难。几个月前我有这种经历。相反,使用group concat将获取单行,其中包含每个人所需的一切。在php端简单提取Group Concated单元格并进行另一个循环或将其放入数组中。这很容易处理。

答案 1 :(得分:2)

我认为您应该将查询分成单独的模型

应该有一个Language模型并保持这个简单

class Language
{
   function getId() { return $id; }
   function getDescription { return $description; }
}


class Person { 

public $person_id; // 1
public $person; // Bob
public $languages; //this will store array of Language object

}

//来自DataAccess

function getPerson($person_id)
{
    $person = new Person();
    //select only from Person table
    //fill $person properties from records
    //$person.person_id = $row['person_id']; etc

    //select from people_languages joined to language where person_id=$person_id
    $person->languages = getLanguagesByPerson($person->person_id); //returns array of languages

    return $person;
}

你现在可以拥有

$person = getPerson(123);
$person->langauges[0]->getId(); //language id
$person->langauges[0]->getDescription(); //language id

$person->langauges[1]->getId(); //language id
$person->langauges[1]->getDescription(); //language id

或循环使用语言

foreach($person->languages as $lang)
{
   //use($lang->getId());
   //use($lang->getDescription();
}

答案 2 :(得分:0)

考虑使用词典

    class Person { 

        public $person_id; // 1
        public $person; // Bob
        //I don't know php but for your idea
        public Dictionary<int,string> languageList; // KeyValuePairs {(5,English),(3,Italiano),(8,Deutsch)}
        .
        . // Functions 
        .

    }