2013-09-22 95 views
0

我現在正在學習php和codeigniter,現在我想結合查詢來快速和有效。我已經做了所有,但還沒有加入最後一張桌子...用多個連接進行查詢

我有4個表格:posts,users,post_categories,categories;

enter image description here

而我想:

  1. 所有職位
  2. 用戶信息使用usr_id
  3. 使用cat_ids
  4. 獲取來自post_categories所有類別ID和獲得的每一個名字使用id_的類別*

這是我結束了......這不是完整的,因爲我已經卡住了與得到的類別名稱爲每個ID_ *

$data = $this->db->select('p.*, u.nickname, u.usr_status, u.usr_rating, pc.*') 
        ->from('posts p') 
        ->join('users u', 'p.usr_id = u.id', 'left') 
        ->join('post_categories pc', 'p.cat_ids = pc.id', 'left') 
        ->limit($limit, $start) 
        ->order_by('p.id', 'desc') 
        ->where('p.active', 1) 
        ->get() 
        ->result_array(); 

任何人都可以幫助我最終在笨此查詢的?

編輯: 在post_categories:ID_1永遠是...但ID_2和ID_3可以留爲NULL(默認值)

回答

2

像下面SQL查詢應爲你工作...

SELECT 
    posts.*, 
    users.nickname, users.user_status, users.usr_rating, 
    c1.category as category_1, 
    c2.category as category_2, 
    c3.category as category_3 
FROM posts 
INNER JOIN users ON user.id = posts.user_id 
INNER JOIN post_dategories ON post_categories.id = posts.cat_ids 
INNER JOIN categories c1 ON post_categories.id_1 = c1.id 
LEFT JOIN categories c2 ON post_categories.id_2 = c2.id 
LEFT JOIN categories c3 ON post_categories.id_3 = c3.id 
WHERE posts.active = 1 

注:LEFT JOINc2c3因爲你說他們是可選

+0

tnx對我來說工作得很好 – user2779986