我现在正在学习php和codeigniter,现在我希望将查询结合起来快速有效。我已经做了所有,但还没有加入最后一张桌子......
我有4个表:帖子,用户,post_categories,类别;
我想得到的是什么:
这就是我最终的结果......它不完整,因为我已经遇到了为每个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();
任何人都可以帮我在codeigniter中结束这个查询吗?
修改 在post_categories中:id_1始终为...但id_2和id_3可以保持为NULL(默认值)
答案 0 :(得分: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 JOIN
c2
和c3
,因为您说它们是可选的