for 发表于 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


for 发表于 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

Michael锐生 发表于 2016-8-2 18:34:14


$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();
页: [1]
查看完整版本: 查询的问题