我有以下查询:
$this->db
->select('SQL_CALC_FOUND_ROWS null as rows
,services.*
,service_categories.*
,categories.*
,table4.*', FALSE)
->from('services')
->where('services.user_id', $user_id)
->join('service_categories', 'service_categories.service_id = services.service_id')
->join('categories', 'categories.cat_id= service_categories.cat_id')
->join('table4', 'table4.service_id= services.service_id', 'left')
->group_by('services.service_id')
->order_by('services.service_id', 'DESC');
$query = $this->db->get();
表格如下所示:
Table: services
------------------------------------------------
| service_id | other_service_columns | user_id |
-----------------------------------------------|
| 23 | other data | 14 |
| 24 | other data | 14 |
------------------------------------------------
Table: service_categories
---------------------------------------
| service_cat_id | cat_id | service_id|
---------------------------------------
| 1 | 924 | 23 |
| 2 | 863 | 23 |
| 3 | 506 | 24 |
| 4 | 510 | 24 |
---------------------------------------
Table: categories
---------------------
| cat_id | cat_name |
---------------------
| 924 | cleaning |
| 863 | washing |
| 506 | drying |
| 510 | scrubbing|
---------------------
表 4 可能没有任何结果,所以我正在做一个左连接。但是,当我按 service_id 分组时,我没有从“service_categories”和“categories”表中获取所有相关类别 - 查询中只返回一行。group_concat 是答案吗?如果是这样,我不确定如何使用它来获得我需要的结果 - 即查询中返回的所有相关类别。请帮忙!
我需要能够通过使用 foreach 对其进行迭代来处理查询结果,以在视图中生成如下内容:
--------------------------------------------------------
| Service ID | Other Service Data | Service Categories |
--------------------------------------------------------
| 23 | Data for Service 23| cleaning, washing |
| 24 | Data for Service 24| drying, scrubbing |
--------------------------------------------------------