所以我有以下(缩写)表:
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'] );
}
答案 0 :(得分: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;