3

我正在codeigniter中做一个项目。这里我想加入三个表

客户(id、姓名、电子邮件、adminId、campaignId、dateAdded、is_deleted)

活动(id,名称,adminId)和

订单(id、名称、成本、添加日期、clientId)。

从这些表中,我想选择(在两个日期之间)添加的客户数量、活动名称和客户的总订单成本。当我加入两个表(客户和活动)时,它返回正确的结果。

我使用的查询是

$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();

任何人都可以有一些想法来做到这一点。在此先感谢

4

1 回答 1

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();

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

于 2013-03-13T04:15:33.237 回答