两个select语句,其中union不起作用

时间:2014-01-06 14:23:35

标签: mysql union

我正在尝试实施以下查询,

     (SELECT
  MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
  final_avg_total.`DRG Definition`,
  final_avg_total.`Provider Id`,
  SUM(final_avg_total.avg_total_payments) AS avg_payments,
  SUM(final_avg_total.avg_covered_charges) AS avg_covered,
  (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_average,
  1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_percentage
FROM final_avg_total
GROUP BY final_avg_total.`Provider Id`
ORDER BY total_average DESC LIMIT 0,5)
Union
 SELECT
  MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
  final_avg_total.`DRG Definition`,
  final_avg_total.`Provider Id`,
  SUM(final_avg_total.avg_total_payments) AS avg_payments,
  SUM(final_avg_total.avg_covered_charges) AS avg_covered,
  (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_average,
  1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_percentage
FROM final_avg_total
GROUP BY final_avg_total.`total_percentage`
ORDER BY total_average DESC LIMIT 0,5

实际上两个查询几乎相同,只有Group By是Differing,但我收到此错误。

5 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT
  MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
  fin' 

2 个答案:

答案 0 :(得分:1)

如果可能,选择较小的问题可能会有所帮助。 如果你

,看看你是否得到相同的结果

创建或替换视图part_one AS ...;

创建或替换视图part_two AS ...;

然后

SELECT * FROM part_one

UNION

SELECT * FROM part_two;

让数据库引擎理解它上面的工作已经帮助了我。也可以帮助代码维护。 如果你得到欺骗,UNION ALL是箭袋中另一个方便的箭头。

答案 1 :(得分:1)

这只是一个有错误的常规UNION http://www.sqlfiddle.com/#!2/ec657/7

这是'相同'的UNION没有错误 http://www.sqlfiddle.com/#!2/ec657/8

唯一的区别是两种情况下的括号,请务必在UNION之后放置括号或将其删除

...
ORDER BY total_average DESC LIMIT 0,5) 
Union
 (SELECT --ADDED PARENTHESIS
  MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
...
ORDER BY total_average DESC LIMIT 0,5) --ADDED PARENTHESIS