从两个表中选择(count,order by,group by)codeigniter

时间:2012-11-16 12:12:02

标签: php codeigniter

我有一个sql命令,它可以工作,但我不能在Codeigniter中使用它,

当我在phpmyadmin中使用它时,它是有效的

  

SELECT online_visitors.page_id,hotels.hotel_name,   count(online_visitors.page_id)count_visit FROM online_visitors,   hotels WHERE online_visitors.page_type ='hotel'AND   online_visitors.is_bot = 0 AND hotels.ID = online_visitors.page_id   通过online_visitors.page_id asc

按online_visitors.page_id排序

但是当我想在codeigniter代码中使用它时,我不能

$this->db->select("page_id , hotel_name");
$this->db->from("hotels");
$this->db->join("online_visitors");
$this->db->where("is_bot", 0);
$this->db->where("page_type", 'hotel');
$this->db->group_by("page_id");
$this->db->order_by("page_id");
$this->db->get();

3 个答案:

答案 0 :(得分:2)

您可以通过使用带连接的CodeIgniter活动记录来尝试此操作

    $this->db->select('ov.page_id , h.hotel_name, count(ov.page_id) as count_visit ');
    $this->db->from('online_visitors as ov');
    $this->db->join('hotels as h','h.ID = ov.page_id');
    $this->db->where('ov.page_type','hotel');
    $this->db->where('ov.is_bot',0);
    $this->db->group_by('ov.page_id');
    $this->db->order_by('ov.page_id',"asc");
    $this->db->get();

答案 1 :(得分:1)

你可以通过提到的两种方法来做到这一点

$query=$this->db->query(
'SELECT online_visitors.page_id , hotels.hotel_name , count(online_visitors.page_id) as count_visit FROM online_visitors , hotels WHERE online_visitors.page_type = 'hotel' AND online_visitors.is_bot = 0 AND hotels.ID = online_visitors.page_id group by online_visitors.page_id order by online_visitors.page_id asc'
);

您可以访问$query作为对象

或者您可以使用Active Record

将其细分

答案 2 :(得分:0)

$this->db->select("online_visitors.page_id , 
hotels.hotel_name,count(online_visitors.page_id) as count_visit");

$this->db>where("online_visitors.page_type = 'hotel'");
$this->db>where("online_visitors.is_bot = 0");
$this->db>where("hotels.ID = online_visitors.page_id");
$this->db->group_by("online_visitors.page_id");
$this->db->order_by("online_visitors.page_id", "asc");