2

您好,我想从共享相同列名的两个表中获取数据。我的表结构是

表病人

 ---------------------------------------
|  id  |  affiliate_id  |  somecolumn  |
 ---------------------------------------
|  1   |    8           |  abc         |          
 ---------------------------------------
|  2   |    8           |  abc         |          
 ---------------------------------------
|  3   |    9           |  abc         |          
 ---------------------------------------

表导

 ---------------------------------------
|  id  |  affiliate_id  |  someothern  |
 ---------------------------------------
|  1   |    8           |  xyz         |          
 ---------------------------------------
|  2   |    8           |  xyz         |          
 ---------------------------------------
|  3   |    3           |  xyz         |          
 ---------------------------------------

现在我的要求是COUNT(ID)在一个查询中从两个表中获取。我想要这样的结果

 ----------------------------------------------------
|  affiliate_id  |  total_patients  |  total_leads  |
 ----------------------------------------------------
|       8        |        2         |       2       |          
 ----------------------------------------------------
|       9        |        1         |       0       |          
 ----------------------------------------------------
|       3        |        0         |       1       |          
 ----------------------------------------------------

我写了以下查询

SELECT `p`.`affiliate_id`, COUNT(p.id) AS `total_patients`, 
   COUNT(cpl.id) AS `total_leads` 
FROM `patients` AS `p` 
   INNER JOIN `leads` AS `cpl` ON p.affiliate_id =cpl.affiliate_id  
GROUP BY `p`.`affiliate_id`

但我没有得到结果。此查询结果仅提供一个具有相同数量的 total_patients 和 total_leads 的会员

4

2 回答 2

3

问题是您需要先获取不同的列表,affiliate_id然后加入其他表以获得结果:

select a.affiliate_id,
  count(distinct p.id) total_patients,
  count(distinct l.id) total_leads
from
(
  select affiliate_id
  from patients
  union 
  select affiliate_id
  from leads
) a
left join patients p
  on a.affiliate_id = p.affiliate_id
left join leads l
  on a.affiliate_id = l.affiliate_id
group by a.affiliate_id;

请参阅带有演示的 SQL Fiddle

于 2013-06-08T14:40:55.057 回答
0

两种方式:

Select l.affiliate_id ,
      count(distinct p.id) patientCount,
      count(distinct l.id) LeadCOunt
From patients p Join leads l
    On l.affiliate_id = p.Affiliate_id
Group By l.affiliate_id 

或者,(假设附属公司在他们自己的桌子上)

Select Affiliate_id,
    (Select Count(*) From Patients
     Where Affiliate_id = a.Affiliate_id) patientCount,
    (Select Count(*) From Leads
     Where Affiliate_id = a.Affiliate_id) LeadCount
From affiliates a
于 2013-06-08T14:44:10.120 回答