0

我现在正在学习 php 和 codeigniter,现在我想结合查询来快速有效。我已经做了所有,但还没有加入最后一张桌子......

我有 4 个表:posts、users、post_categories、categories;

在此处输入图像描述

我想得到什么:

  1. 所有帖子
  2. 使用 usr_id 的用户信息
  3. 使用 cat_ids 从 post_categories 获取所有类别 id
  4. 并使用 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();

任何人都可以帮助我在codeigniter中结束这个查询吗?

编辑: 在 post_categories 中:id_1 总是......但 id_2 和 id_3 可以保持为 NULL(默认值)

4

1 回答 1

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

于 2013-09-22T15:20:01.110 回答