如何在同一个表中多次JOIN来检索不同的结果

时间:2013-11-24 14:44:34

标签: php mysql codeigniter activerecord

我需要同时请求记录,但不知道如何将它们彼此分开以避免它们被合并。

有一个表categories,其中CID列代表组件ID ,用于分隔类别:

id  cid     title
1   1       News
2   1       Events

3   2       Users
4   2       Administrators

5   3       Guests
6   3       Registered

这是components表:

id  title
1   Content
2   Members
3   Access level

我需要从数据库中检索结果,以便在content_list_view.php中打印这些变量:

<?php foreach($results as $item):?>
    ID: <?php echo $item->id;?> <br/>
    Title: <?php echo $item->title;?> <br/>
    Category: <?php echo $item->category;?> <br/>
    Access: <?php echo $item->access;?> <br/>
<?php endforeach;?>

使用CodeIgniter的ActiveRecords,我在content_model.php进行查询:

public function get_content_list(){

    $this->db
        ->select('
            content.id,
            content.title,
            categories.title AS category,
            categories.title AS access
        ')
        ->join('categories', 'content.catid = categories.id')
        ->join('categories AS alvl', 'content.alvl = alvl.id');

    $query = $this->db->get($this->_table_name);

    if($query->num_rows() > 0)
        return $query->result();
    else
        return FALSE;

}

毕竟,这是我在视图中得到的, Category Access 是相同的。访问权限应已注册

ID: 1
Title: Some article test news
Category: News
Access: News

在JOINING表时如何分离记录的任何建议?

1 个答案:

答案 0 :(得分:1)

问题出在选择中,因为您没有分配alvl,而且始终来自categories 试着改变这个:

$this->db
        ->select('
            content.id,
            content.title,
            categories.title AS category,
            categories.title AS access
        ')
        ->join('categories', 'content.catid = categories.id')
        ->join('categories AS alvl', 'content.alvl = alvl.id');

到此:

$this->db
        ->select('
            content.id,
            content.title,
            categories.title AS category,
            alvl.title AS access
        ')
        ->join('categories', 'content.catid = categories.id')
        ->join('categories AS alvl', 'content.alvl = alvl.id');