用户
 找回密码
 入住 CI 中国社区
搜索
查看: 1072|回复: 2
收起左侧

[版本 3.x] 查询的问题

[复制链接]
发表于 2016-8-2 16:35:03 | 显示全部楼层 |阅读模式
本帖最后由 for 于 2016-8-2 17:01 编辑

三个数据表
tableA

aid atitle acontent adel astyle anode


tableB

bid bname bschool

tableC

cid cname cdel


我想读出 tableA的所有数据,并且把bname和cname通过bid=astyle, cid=anode的关系读出来,并且 adel=0, cdel=0


如果不通过 sql 语句的方式,该怎么写呢?


        $this->db->select('*');
        $this->db->from("tableA,tableB,tableC");
        $this->db->where("tableA.adel",0);
  ...

这样写法不对,正确的写法是?
更详细点,这样的语句,在 ci 的model中怎么写?

select *, (select bname from tableB b where bid = a.astyle) as bname, (select cname from tableC b where cid = a.anode and cdel=0) as cname from tableA a where a.adel = 1


 楼主| 发表于 2016-8-2 16:49:11 | 显示全部楼层
本帖最后由 for 于 2016-8-2 17:00 编辑

可能没有表述清楚,我想要的结果是

1. 读出所有的 tableA 的数据
2. 根据 astyle 和 bid 对应的关系,显示出 bname,没有对应关系的则不显示
3. 根据 anode 和 cid 对应的关系,显示出 cname,没有对应关系的则不显示,如果cdel=1 也不显示
更详细点,这样的语句,在 ci 的model中怎么写?

select *, (select bname from tableB b where bid = a.astyle) as bname, (select cname from tableC b where cid = a.anode and cdel=0) as cname from tableA a where a.adel = 1
发表于 2016-8-2 18:34:14 | 显示全部楼层
PHP复制代码
 
$this->db->select('aid, atitle, acontent, adel, astyle, anode, bname, cname')
        ->join(tableB, bid = astyle, 'left')
        ->join(tableC, cid = anode, 'left')
        ->get_where(tableA, array('adel' => 0, 'cdel' => 0))
        ->result_array();
 
复制代码

本版积分规则