如何联接两个表并获得以下结果?

时间:2018-10-22 09:22:50

标签: php codeigniter

我的广告系列表数据当前是这样的

id    campaign_name
 1    florist
 2    dentist
 3    restaurants
 4    realestate

还有我的第二张桌子(主角)

id          campaign_id       business_id
 1               1                13456
 2               1                34563
 3               3                65987
 4               2                45654
 5               3                45632

我想按JOIN和GROUP BY列出所有广告系列名称,以及相应广告系列的总潜在客户。(codeigniter)

campaign_name                No. of leads
florist                            2
dentist                            1
restaurants                        2
realestate                         0

3 个答案:

答案 0 :(得分:1)

您可以使用active record/ query builder作为

来获取期望的数据
$this->db->select ( 'c.campaign_name,count(l.business_id) as no_of_leads' ,false)
        ->from ( 'campaign as c' )
        ->join ( 'leads l', 'c.id = l.campaign_id','left')
        ->group_by( 'c.campaign_name')
        ->get();

答案 1 :(得分:1)

您应该使用左联接

$this->db->select('campaign_name, COUNT(campaign_id) AS `No. of leads`');
$this->db->from('campaign');
$this->db->join('lead', 'campaign.id = lead.campaign_id', 'left');
$this->db->group_by( 'campaign.campaign_name' )
$result = $this->db->get();

答案 2 :(得分:0)

其他人发布了查询生成器代码,因此这是您需要的Raw SQL

fromObject

左联接很重要,因为您要计算这个数字:

SELECT
   c.campaign_name,
   COUNT(l.id) as total_leads
FROM
   campaigns AS c
LEFT JOIN
   leads AS l ON c.id = l.campain_id
GROUP BY c.id

您在 realestate 0 中有一个ID为4的记录,而在campaigns中没有该活动ID的记录。我还将对PKEY进行计数和分组,您将获得更好的索引编制和更高的可靠性(因为我们知道它们是唯一的)。