SQL使用2个左连接返回不正确的数据

时间:2012-06-01 07:37:48

标签: mysql

我编写了一个MYSQL脚本,它返回不正确的数据。我对SQL非常流利,但是这个查询没有返回正确的结果。有人可以看看,看看有什么事情发生。问题是noOfBids和noOfRatedTimes。两列的值相同,也是大值。

    select
           a.user_name as userName,
           coalesce(count(b.sp_user_name),0) as noOfBids,
           coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
           coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
           coalesce(ROUND(AVG(d.user_rate),2),0)
    from users a
    left join project_imds b
       on b.sp_user_name = a.user_name
    left join projects c
       on b.project_code = c.project_code
    left join sp_user_rating d
       on d.sp_user_name = b.sp_user_name
    where a.user_type = 'SP'
    and a.active = 'Y'
    group by a.user_name
    order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;

我已经创建了一个解决方法,通过创建临时表来获取avg值并将其加入主查询。

2 个答案:

答案 0 :(得分:0)

由于我不知道查询背后的数据细节,这只是猜测。但也许你宁愿加入" sp_user_rating"直接到"用户",改变

left join sp_user_rating d
   on d.sp_user_name = b.sp_user_name

left join sp_user_rating d
   on d.sp_user_name = a.user_name

答案 1 :(得分:-1)

select
       a.user_name as userName,
       coalesce(count(b.sp_user_name),0) as noOfBids,
       coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
       coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
       coalesce(ROUND(AVG(d.user_rate),2),0)
from users as a
left join project_imds as b
   on b.sp_user_name = a.user_name
left join projects as c
   on b.project_code = c.project_code
left join sp_user_rating as d
   on d.sp_user_name = b.sp_user_name
where a.user_type = 'SP'
and a.active = 'Y'
group by a.user_name
order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;