1

所以我有以下(缩写)表:

resource
id | name

resource_category
resource_id | category_id

category
id | name

当我想获取资源和所有分配的类别时,我使用以下 sql:

SELECT resource.id. resource.name, category.id, category.name FROM resource
LEFT JOIN resource_category ON resource_category.resource_id = resource.id
LEFT JOIN category ON category.id = resource_category.category_id

这将获得以下资源

resource.name1 | 1 | category1
resource.name1 | 2 | category2
resource.name1 | 5 | category5
resource.name2 | 5 | category5
resource.name2 | 6 | category6
resource.name2 | 1 | category1

然后我循环并将结果压缩到数组中

foreach( $results as $result ) {
    $resources[$result['id']]['resource'] = $result;
    $resources[$result['id']]['categories'][$result['category_id']] =
    $result['category_name'];
}

然后我会有一个资源和所有它的类别。

我遇到的问题是,当我开始进行分页并使用 LIMIT 时,结果给出了 10 个结果,但是由于单个资源有多个结果,所以当我压缩它时,我得到 2 个实际资源而不是 10 个。任何建议?

我试图远离下面的代码:

foreach( $results as $result ) {
      $resources[$result['id']]['resource'] = $result;
      $resources[$result['id']]['categories'] =
      $this->resource_model->get_categories( $result['id'] );
}
4

1 回答 1

1

你的问题的答案是你需要一个稳定的排序。显式添加order by

SELECT resource.id. resource.name, category.id, category.name
FROM resource
LEFT JOIN resource_category ON resource_category.resource_id = resource.id
LEFT JOIN category ON category.id = resource_category.category_id
order by resource.id, category.id;

如果您只是将这些放入数组中,请尝试group_concat()

SELECT resource.id. resource.name,
       group_concat(category.id) as cids,
       group_concat(category.name) as cnames
FROM resource
LEFT JOIN resource_category ON resource_category.resource_id = resource.id
LEFT JOIN category ON category.id = resource_category.category_id
group by resource.id;
于 2013-09-11T18:59:19.333 回答