[英]join three tables in codeigniter with one to many relation
我在codeigniter做一個項目。我想加入三個表
客戶(id,name,email,adminId,campaignId,dateAdded,is_deleted)
廣告系列(ID,名稱,adminId)和
訂單(id,name,cost,dateAdded,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();
任何人都可以有一些想法這樣做。謝謝你提前
我通過計算不同的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();
我不認為這是正確的方法。有沒有更好的方法來做到這一點。謝謝你的支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.