doubu0897 2014-11-23 19:31
浏览 51
已采纳

Codeigniter - MySql:使用另一个表的ID加入一个表的三个列值

I have a category table that names each category, then I have an artwork table that has three columns offering three different categories per art piece. I am building a select query that will look in all three columns of one category and join the category table so I can get the category name. I have alias' for each join, but my query is still returning null values for category_id2 and category_id3. Any assistance is greatly appreciated.

From Codeigniter Model:

function category_search($category) {
    $this -> db -> select('a.id, a.artist_fname, a.artist_lname, b.artist_id, b.sm_file_name, b.category_id, b.category_id2, b.category_id3, c.id, c.category');
    $this -> db -> from('ap_mini_artist a', 'ap_mini_artwork b', 'ap_art_categories c', 'ap_art_categories c2', 'ap_art_categories c3');
    $this -> db -> where('c.category', $category, 'after');
    $this -> db -> join('ap_mini_artwork b', 'b.artist_id=a.id', 'left');
    $this -> db -> join('ap_art_categories c', 'c.id=b.category_id', 'left');
    $this -> db -> join('ap_art_categories c2', 'c2.id=b.category_id2', 'left');
    $this -> db -> join('ap_art_categories c3', 'c3.id=b.category_id3', 'left');
    $query = $this -> db -> get();
    return $query -> result();
}

From Controller if needed:

public function category_search() {

    $category = $this -> input -> post('categoryValue');
    $query = $this -> mini_show_model -> category_search($category);

    if (!empty($query)) {
        $json = json_encode($query);
        print $json;
    } else {
        echo "Your query is empty, please try again.";

    }
}

Thanks for your help!

  • 写回答

1条回答 默认 最新

  • douerqu2319 2014-11-24 12:28
    关注

    You do not need three joins with the category table. Instead join with all three fields as an accepted match:

    select a.id, a.artist_fname, a.artist_lname, b.artist_id, b.sm_file_name, b.category_id, b.category_id2, b.category_id3, c.id, c.category
    from ap_mini_artist a
    left join ap_mini_artwork b on b.artist_id = a.id
    left join ap_art_categories c on c.id in (b.category_id, b.category_id2, b.category_id3)
    where c.category LIKE ?
    

    Regarding your active record query:

    • When you have joins you do not need to repeat table names in the from clause
    • where function has no after arguments, change it to db->like(c.category', $category, 'after'
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件