在codeigniter中使用一对多关系连接三个表

时间:2013-03-12 08:11:20

标签: php codeigniter join

我在codeigniter做一个项目。我想加入三个表

客户(id,name,email,adminId,campaignId,dateAdded,is_deleted)

广告系列(ID,name,adminId)和

订单(id,name,cost,dateAdded,clientId)。

从这些表中我想选择(在两个日期之间)添加的客户数量,广告系列名称和客户的总订单成本。当我加入两个表(客户和广告系列)时,它会返回正确的结果。< / p>

我使用的查询是

$this->db->select('clients.id AS my_client,
    clients.name AS client_name,
    campaign.name AS campaign_name,
    DATE(clients.dateAdded) as client_date,
    COUNT(clients.id) AS num_rows');

$this->db->from('clients');
$this->db->where('clients.adminId', $adminId);
$this->db->where('DATE(clients.dateAdded) >=', $from_date);
$this->db->where('DATE(clients.dateAdded) <=', $to_date);
$this->db->join('campaign', 'campaign.id = clients.campaignId', 'left');
$this->db->group_by('campaign_name');
$query = $this->db->get();
return $query->result();

但是当我加入三个表(客户,广告系列,订单)时,它没有返回正确的结果。客户端和订单之间的关系是一对多。如果一个客户端可以有多个订单。所以它不会给出正确的两个日期之间添加的客户端总数的值。我用来连接三个表的连接查询是

$this->db->select('clients.id AS my_client,
    clients.name AS client_name,
    campaign.name AS campaign_name,
    DATE(clients.dateAdded) AS client_date,
    SUM(order.cost) AS order_cost,
    COUNT(clients.id) AS num_rows');

$this->db->from('clients');
$this->db->where('clients.adminId', $adminId);
$this->db->where('clients.is_deleted', 0);
$this->db->where('DATE(clients.dateAdded) >=', $from_date);
$this->db->where('DATE(clients.dateAdded) <=', $to_date);
$this->db->join('campaign', 'campaign.id = clients.campaignId', 'left');
$this->db->join('order', 'order.clientId = clients.id', 'left');
$this->db->group_by('campaign_name');
$query = $this->db->get();
return $query->result();

任何人都可以有这样的想法。谢谢提前

1 个答案:

答案 0 :(得分:2)

我通过计算不同的client.id(COUNT(DISTINCT(clients.id)))来获得预期的结果,用于添加的客户端数量,

$this->db->select('clients.id AS my_client,
    clients.name AS client_name,
    campaign.name AS campaign_name,
    DATE(clients.dateAdded) AS client_date,
    SUM(order.cost) AS order_cost,
    COUNT(DISTINCT(clients.id)) AS num_rows'); //changed the code here from COUNT(clients.id) AS num_rows

$this->db->from('clients');
$this->db->where('clients.adminId', $adminId);
$this->db->where('clients.is_deleted', 0);
$this->db->where('DATE(clients.dateAdded) >=', $from_date);
$this->db->where('DATE(clients.dateAdded) <=', $to_date);
$this->db->join('campaign', 'campaign.id = clients.campaignId', 'left');
$this->db->join('order', 'order.clientId = clients.id', 'left');
$this->db->group_by('campaign_name');
$query = $this->db->get();
return $query->result();

我不认为这是正确的方法。有没有更好的方法来做到这一点。感谢您的支持。