我有一个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
在这里拨弄:http://sqlfiddle.com/#!9/7ea891/1
学生A正常工作,但学生B不能正常工作。
答案 0 :(得分:1)
默认情况下,UNION是UNION DISTINCT,这意味着任何重复的行都将在子查询中被过滤掉。将其更改为UNION ALL。参见What is the difference between UNION and UNION ALL?
答案 1 :(得分:1)
您需要使用全部联合,请尝试以下查询,如果您使用显式联接,则更好
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