繁体   English   中英

Codeigniter-MySql:将一个表的三个列值与另一个表的ID连接起来

[英]Codeigniter - MySql : Join three column values of one table with the ID of another table

我有一个类别表,为每个类别命名,然后有一个艺术品表,其中包含三列,每个艺术品提供三个不同的类别。 我正在构建一个选择查询,该查询将在一个类别的所有三列中查找并加入类别表,以便我可以获取类别名称。 每个连接我都有别名”,但我的查询仍然为category_id2和category_id3返回空值。 非常感谢您的协助。

从Codeigniter模型:

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();
}

从控制器(如果需要):

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.";

    }
}

谢谢你的帮助!

类别表不需要三个联接。 而是将所有三个字段作为可接受的匹配项加入:

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 ?

关于活动记录查询:

  • 有联接时,无需在from子句中重复表名
  • where函数没有after参数,请将其更改为db->like(c.category', $category, 'after'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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