2015-11-22 63 views
0

分開後,我有這樣的如何從逗號笨

tbl_post

+-----------+--------------+ 
| post_id | post_content | 
+-----------+--------------+ 
| 1   | contentone | 
+-----------+--------------+ 

tbl_category

+-------------+---------------+ 
| category_id | category_name | 
+-------------+---------------+ 
|   1 | Politic  | 
|   2 | Social  | 
|   3 | Economy  | 
+-------------+---------------+ 

tbl_category_post

+------------------+-------------+---------+ 
| category_post_id | category_id | post_id | 
+------------------+-------------+---------+ 
|    1 |   1 |  1 | 
|    2 |   2 |  1 | 
|    3 |   3 |  1 | 
+------------------+-------------+---------+ 
表每個ID選擇從其他表中的多個數據

然後,我想這樣的

+--------------+--------------------------+ 
| post_content |   category   | 
+--------------+--------------------------+ 
|   1 | Politic, Social, Economy | 
+--------------+--------------------------+ 

,然後輸出如何顯示這樣使用笨的數據,我真的很困惑可言,誰能請幫幫我!

+1

使用數據庫 「內連接」 的聲明。 http://stackoverflow.com/questions/16013364/inner-join-with-3-tables-in-mysql – Xorifelse

回答

0

編輯:使用CodeIgniter(未測試):

$this->db->select('post_id, GROUP_CONCAT(tc.category_name) AS category_name') 
->from('tbl_category_post tcp') 
join->('tbl_category tc', 'tc.category_id=tcp.category_id', 'left') 
->group_by('tcp.post_id'); 

我想你需要PHP循環方法循環這一點。

使用MySQL GROUP_CONCAT功能:

SELECT post_id, GROUP_CONCAT(tc.category_name) AS category_name 
FROM tbl_category_post tcp 
LEFT JOIN tbl_category tc ON tc.category_id=tcp.category_id 
GROUP BY tcp.post_id 
+0

嗨艾哈邁德,然後如何創建到codeigniter活動記錄,以及如何循環foreach,無論如何thaks之前它是在MySQL上工作。 –

+0

謝謝兄弟,你救了我的命:) –