是否应该使用SQL联合或联接?

时间:2012-05-02 17:44:58

标签: mysql sql join union

我正在尝试获取邮政编码以及我拥有的2张桌子,患者和医生的邮政编码号码。我通过计算邮政编码得到#of电话,就好像有5名患者使用邮政编码79555然后计数将是5.如果患者表有3个人有拉链且医生表有4个,它应该返回邮政编码和7.我尝试了下面的工会。乍一看它看起来像我想要的,但我想要总结一下重复的邮政编码,我可以在联盟中使用sum函数吗?或者我必须创建一个连接?

SELECT zip_code, COUNT(zip_code) AS Num_Patient_Calls FROM patients GROUP BY zip_code
UNION ALL
SELECT zip_code, COUNT(zip_code) AS Num_Physician_Calls FROM physicians GROUP BY zip_code

编辑:解决方案 我使用Gordon和dweiss的回复来生成这个SQL代码。它执行我想要的操作,即从不相关的表中获取两个可能具有或不具有相同值的字段,计算在每个表中具有该值的记录数,然后对两个表中的结果求和。示例:患者表中的邮政编码99709的6个实例,医师表中的1个,显示的值为99709 - 7.

SELECT zip_code, SUM(Patient_Calls) FROM (
    SELECT zip_code, COUNT(zip_code) AS Patient_Calls FROM patients GROUP BY zip_code
    UNION ALL
    SELECT zip_code, COUNT(zip_code) AS Physician_Calls FROM physicians GROUP BY zip_code
) AS new_table
GROUP BY zip_code ORDER BY `new_table`.`zip_code` 

2 个答案:

答案 0 :(得分:3)

由于这些是不相关的表,您希望使用UNION。此外,COUNTSUM是不同的功能,在这种情况下,您正在寻找COUNT。 SUM将添加所有值,而COUNT将为您提供GROUP中找到行的次数。 这样的事情怎么样?

SELECT zip_code,COUNT(*) FROM (
SELECT zip_code AS Num_Patient_Calls FROM patients
UNION ALL
SELECT zip_code AS Num_Physician_Calls FROM physicians
) AS new_table
GROUP BY zip_code

答案 1 :(得分:1)

要回答您的问题,您需要UNION ALLFULL OUTER JOIN,因为您的邮政编码只能使用一种类型的电话。

我会将结果结构如下:

select zip_code, sum(Patient_Call) as Num_Patient_Calls,
       sum(Physician_Call) as Num_Physician_Calls,
       sum(Patient_Call + Physician_Call) as Num_Calls
from 
(
  (SELECT zip_code, 1 AS Patient_Call, 0 as Physician_Call
   FROM patients
  )
  UNION ALL
  (SELECT zip_code, 0 AS Patient_Call, 1 as Physician_Call
   FROM physicians
  )
) calls
GROUP BY zip_code

如果您多次运行此查询,则可以尝试在每个子查询中进行聚合,以查看是否更快(例如,如果zip_code上有索引,则可能更快)。