SQL 连接 2 个表,并考虑隐藏字段/标志



我的数据库中有 2 个表,我尝试使用 codeignighter 连接,这些表与productscategories_has_products,以便我可以获取visible的产品列表。

如果visible== 0,那么我不想得到这些产品。

category表与此无关,因为我已经知道要为其收集数据的类别 ID,但是我认为 Id 最好包括仅用于 ref 的设计/表。

我的尝试

我自己尝试过这个,但是SQL有点生疏

$this->db->join('categories_has_products', 'categories_has_products.product_id = products.id', 'left') ->where('visible',1)->get('products');

产品

id | name | visible 
---+------+--------
1  | abc  | 1
2  | def  | 1
3  | ghi  | 0
4  | jkl  | 1
5  | mno  | 1

Categories_has_Products

id | category_id | product_id| 
---+--------+
1  | 1      | 1
2  | 1      | 3
3  | 1      | 4

类别

id | name   | 
---+--------+
1  | fruit  | 
1  | drinks | 

预期成果

id | name | visible 
---+------+---------
1  | abc  | 1
4  | jkl  | 1

根据所需的结果集,不应使用 LEFT 联接。这样的东西应该有效(未经测试,自然)

    $this->db->select('products.*');
    $this->db->from('products');
    $this->db->join('categories_has_products', 'categories_has_products.product_id = products.id', 'INNER');
    $this->db->where('products.visible !=', 0);

最新更新