【问题标题】:Join on same column name加入相同的列名
【发布时间】:2013-06-04 17:31:05
【问题描述】:

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

表病人

 ---------------------------------------
|  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 的会员

【问题讨论】:

  • 真正想要的是一个完整的外连接,MySQL 不支持它......

标签: mysql join inner-join


【解决方案1】:

问题是您需要先获取不同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 with Demo

【讨论】:

    【解决方案2】:

    两种方式:

    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
    

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多