2013-09-22 66 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