0

我写了一个 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;

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

4

2 回答 2

0

Since I don't know the specifics of the data behind your query, this is only a guess. But perhaps you'd rather join "sp_user_rating" directly to "users", changing

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

to

left join sp_user_rating d
   on d.sp_user_name = a.user_name
于 2012-06-01T07:43:50.307 回答
-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;
于 2012-06-01T07:41:59.343 回答