我有几张桌子:
table user:
id firstname lastname
1 John Doe
2 Jane Skith
3 will Smith
...
table member:
member_id member_user_id member_status member_activated_by
10 1 yes partner 1
11 1 yes partner 2
12 1 yes partner 3
13 2 yes partner 2
14 3 no ----
...
table points:
points_id points_user_id points_value points_date
10 1 10 2012-02-15
11 2 15 2012-02-15
12 2 20 2012-02-15
13 1 5 2012-02-15
14 3 30 2012-02-15
15 1 12 2012-02-15
...
So results SHOULD be:
id1 - John Doe: 27 Points
id2 - Jane Skith: 35 Points
id3 - will Smith: nothing (not activated)
问题是,id1带来81点(因为他被激活了3次......)
这是我当前的mysql字符串(缩短...)
SELECT points_user_id, SUM( points_value ) AS points_total, id, firstname, lastname
FROM user
JOIN member ON member.member_user_id = user.id
JOIN points ON points.points_user_id = user.id
WHERE 1
AND member_status = 'yes'
GROUP BY points_user_id
ORDER BY points_total DESC
LIMIT 0 , 100
..到目前为止,几乎"按需工作。
但是:用户可能拥有激活他的sevaral合作伙伴"进入激活"表。
现在,当这个被调用时,我得到了一个重复的points_total(它将被计算多次,因为uesr已被合作伙伴激活......)这在排名列表中没有多大意义......
我怎样才能得到"一个"每个user_id的points_total
希望你明白,我想要实现的目标......非常感谢!
答案 0 :(得分:2)
我认为这应该有效,而不是使用激活连接进行子选择,每个user_id只能获得一行,然后加入此子选择,我不确定这是否是MySql sintax,但它应该显示给你办法。唯一的注意是,您在内部查询中选择的字段可能不会更改为同一个user_id
SELECT user_id, SUM( point_row ) AS points_total, user_data...,...
FROM points
JOIN user_data AS UD
ON UD.user_id = points.user_id
JOIN ( SELECT field1,field2,field3, MAX(activation.user_id) as user_id
FROM activation WHERE activation_info = 'yes'
GROUP BY field1,field2,field3 AS ACTIV ) AS ACTIV
ON user_data.user_id = AS ACTIV.user_id
WHERE points.points_status = '1'
AND ACTIV.activation_info = 'yes'
GROUP BY points.user_id
ORDER BY total DESC
LIMIT 0 , 100
答案 1 :(得分:0)
很难说没有显示完整的SELECT语句。大多数情况下,您可能需要从select中删除user_id不唯一的所有字段。拥有非唯一值会产生跨多行的结果。此外,您似乎应该按points_total排序,而不是总计。