codeigniter加入了很多对很多LIMIT

时间:2013-06-21 10:49:14

标签: php mysql codeigniter join group-concat

我有三张桌子:

products: model_id, model(unique),
groups: group_id, code(unique), 
products_groups: pg_id, model_id_fk, group_id_fk

products_groups表用于表'产品'和'组'之间的“多对多”关系。

我的左连接:

$this->db->select('model_id, model, code');
$this->db->from('products');
$this->db->join('products_group', 'products_group.model_id_fk = products.model_id', 'left');
$this->db->join('groups', 'groups.group_id = products_groups.group_id_fk', 'left');
$query = $this->db->get()->result_array();

结果:

|-------------------------|
| model_id | model | code |
|-------------------------| 
| 0        | 1000  | 15   | 
| 0        | 1000  | 20   | 
| 0        | 1000  | 30   | 
| 1        | 2000  | 15   | 
| 1        | 2000  | 20   |
|-------------------------|

我想要的是什么:

|-------------------------------|
| model_id | model | code       |
|-------------------------------|
| 0        | 1000  | 15,20,30   |
| 1        | 2000  | 15,20      |
|-------------------------------|

解(?): 我想到的第一件事是“按products.model_id排序”,然后逐行检查结果,合并具有相同“model_id”的行并连接它们的“代码”值。

问题: 我想做分页,如果我对查询进行限制,行的合并会弄乱行数。

所以我需要建议,我该怎么做?

P.S。这只是信息的一部分,'产品'表与第二个表有一个“多对多”关系,与第三个表有“一对多”关系。也许会增加一个“多对多”关系。

2 个答案:

答案 0 :(得分:0)

使用GROUP_CONCAT

GROUP_CONCAT(`groups`.`code`) AS "codes"

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

答案 1 :(得分:0)

groupby model_id和group_concat代码