简体   繁体   中英

How to JOIN multiple times the same table to retrieve different results

I need to request the records from the same time but don't know how to separate them one from another to not get them merged.

There is a table categories with column CID which represent Component ID to separate the categories:

id  cid     title
1   1       News
2   1       Events

3   2       Users
4   2       Administrators

5   3       Guests
6   3       Registered

And here is a components table:

id  title
1   Content
2   Members
3   Access level

I need to retrieve a results from a database so I could print these variables in my 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;?>

Using CodeIgniter's ActiveRecords, I'm doing a query in 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;

}

After all, this is what I get in my view, Category and Access are the same. Access should be Registered :

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

Any advice how to separate the records when JOINING tables ?

The problem is into the select, because you aren't assign alvl and it takes always from categories try to change this:

$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');

to this:

$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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM