我有一个 UNION 语句来合并来自两个不同表 (MySQL 5.6) 的学生的分数。它返回不一致的结果。当我独立运行每个语句时,它们会为所有学生生成正确的结果。当我将它们与 UNION 组合时,它对除一个学生以外的所有人都是正确的。
更奇怪的是,如果我从第一个查询中删除任何一个添加的项目,所有记录的总和都是正确的。
例如,从查询中删除 sum(ifnull(owl_tracker.pre_req_points,0))
或 sum(ifnull(owl_tracker.bonus_points,0))
会导致它为所有学生返回正确的结果。
select first_name, last_name, location, sum(total_points) as total_points from (
select first_name, last_name, location, (
sum(ifnull(owl_tracker.pre_req_points,0)) +
sum(ifnull(owl_tracker.bonus_points,0)) +
sum(ifnull(owl_tracker.a_points,0))) AS total_points
from products, students_products, students
在这里 fiddle :http://sqlfiddle.com/#!9/7ea891/1
学生 A 正确,但学生 B 不正确。
最佳答案
你需要使用 union all,试试下面的查询,如果你使用 explicit join 会更好
http://sqlfiddle.com/#!9/7ea891/7
select first_name, last_name, location, sum(total_points)
from
(
select first_name, last_name, location, (
sum(ifnull(owl_tracker.pre_req_points,0)) +
sum(ifnull(owl_tracker.bonus_points,0)) +
sum(ifnull(owl_tracker.a_points,0))) AS total_points
from products left join students_products on products.product_id = students_products.product_id
left join students on students_products.student_id = students.unique_id
left join owl_tracker on students.unique_id = owl_tracker.student_id
where products.product_type in ('Group_Course','Full_Course') and products.test_date_id = '19' and unique_id in ('4833' ,'4956')
group by first_name, last_name, location
union all
select first_name, last_name, location,
sum(ifnull(owl.points,0)) AS total_points
from products left join students_products on
products.product_id = students_products.product_id
left join students on students_products.student_id = students.unique_id
left join owl on students.unique_id = owl.student_id
where products.product_type In ('Group_Course' ,'Full_Course') and
products.test_date_id = '19' and
unique_id in( '4833' , '4956')
group by first_name, last_name, location) t_union
group by first_name, last_name, location
order by location, last_name
关于MySQL Union 返回不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52306231/