MySQL - 使用主表将表连接两次

时间:2011-05-05 11:03:23

标签: mysql join left-join

我不确定是否可以这样做。但我只想在这里咨询专家。

我的情况是: 我有一个表tbl_campaign,它基本上存储一个与名为tbl_campaign_user的表有一对多关系的广告系列,其中在广告系列中选择的用户与广告系列ID一起存储(tbl_campagin_user.cu_campaign_id = tbl_campaign.campaign_id)。

第二个表(tbl_campaign_user)的状态字段为0/1,表示未发送/已发送。我想编写一个单独的SQL查询来读取广告系列数据以及已发送和未发送的广告系列用户数(这就是为什么我在第二个表上加入两次)。 我在下面尝试了这个,但是得到的数量与发送和未发送的数量相同。

SELECT `tbl_campaign`.*, 
COUNT(sent.cu_id) as numsent, 
COUNT(unsent.cu_id) as num_unsent   FROM (`tbl_campaign`) 

LEFT JOIN tbl_campaign_user as sent on  (sent.cu_campaign_id = tbl_campaign.campaign_id and sent.cu_status='1')

LEFT JOIN tbl_campaign_user as unsent on  (unsent.cu_campaign_id = tbl_campaign.campaign_id and unsent.cu_status='0')


WHERE `tbl_campaign`.`campaign_id` = '19'  

我通过将查询分为两部分来尝试调试: =>

SELECT `tbl_campaign`.*, 

COUNT(unsent.cu_id) as num_unsent   FROM (`tbl_campaign`) 

Left join tbl_campaign_user as unsent on  (unsent.cu_campaign_id = tbl_campaign.campaign_id and unsent.cu_status='0')

WHERE `tbl_campaign`.`campaign_id` = '19'

以上工作完全符合要求。下面的那个也是如此:

=>

SELECT `tbl_campaign`.*, 
COUNT(sent.cu_id) as numsent   FROM (`tbl_campaign`) 

Left join tbl_campaign_user as sent on  (sent.cu_campaign_id = tbl_campaign.campaign_id and sent.cu_status='1')

WHERE `tbl_campaign`.`campaign_id` = '19' 

我不确定在合并两者时我做错了什么。我知道我对连接知之甚少,可能是一个概念上的错误?请有人帮帮我吗?

提前谢谢!

1 个答案:

答案 0 :(得分:2)

你只需要加入tbl_campaign_user一次 count(sum,whatever)cu_status为零/一的次数。

SELECT `tbl_campaign`.id, 
count(u.id) as num_all_campaign_users
sum(u.cu_status) as num_sentcampaign_users, 
count(u.id) - sum(u.cu_status) as num_unsent_campaign_users   
FROM `tbl_campaign` c 
LEFT JOIN tbl_campaign_user as u on (u.cu_campaign_id = c.campaign_id)
WHERE `tbl_campaign`.`campaign_id` = '19'  
group by `tbl_campaign`.id

请注意,这是一种伪代码,您可能需要详细说明 select子句和group by子句中的sum / count。