mysql , codeigniter active record class [closed]

2019-09-29 08:46发布

问题:

table1

house_id|house_name|status

  1     |     A    |  1
  2     |     B    |  1
  3     |     C    |  0
  4     |     D    |  1
  5     |     E    |  1
  6     |     F    |  1

table1

house_id| image

   2    | img1.jpg
   2    | img2.jpg
   1    | img3.jpg
   4    | img4.jpg
   1    | img5.jpg
   4    | img6.jpg
   3    | img7.jpg

I want select all house_id from table1 where status =1 (descending) , select distinct image from table2, for each house_id of table1 .

Finally output show bellow :

Output

house_id|house_name|image

   6    |    F     |NULL
   5    |    E     |NULL
   4    |    D     |img4.jpg
   2    |    B     |img1.jpg  
   1    |    A     |img3.jpg  

please help me code with normal mysql or CI active record class method ..

回答1:

try this out....(normal mysql)

SELECT t1.*,t2.image FROM table1  t1
LEFT JOIN table2 t2 on t1.house_id=t2.house_id
WHERE t1.status= 1 GROUP BY t1.house_id ORDER BY house_id desc

active record...

$this->db->select(t1.*,t2.image);
$this->db->from('table1'.' t1');
$this->db->join('table2'.' t2','t1.house_id=t2.house_id','left');
$this->db->where('t1.status',1);
$this->db->group_by("t1.house_id"); 
$this->db->order_by("house_id");


标签: codeigniter