如果列的SUM达到某个数字,则返回行

时间:2013-10-12 15:49:50

标签: mysql

这是mybb_reputation表

mybb_reputation table

如果所有这些行的rid总和达到3,我想获取行reputation的数量。例如,在这种情况下(请参见上图)如果我运行一个查询它应该返回除1,2和3(所以总声誉变为3)或者它只返回rid 5,因为它的声誉正好等于3

我尝试过运行此查询;

SELECT * FROM mybb_reputation WHERE SUM(reputation) = 3;

但由于MySQL知识有限,显示错误,例如:#1111 - 无效使用群组功能

请帮忙!

4 个答案:

答案 0 :(得分:1)

这个答案与我的评论有关 -

查找1条记录(简单)

SELECT tmp1.rid AS rid
FROM mybb_reputation AS tmp1
WHERE tmp1.reputation = 3;

查找任意2条记录(使用<因为关系的顺序与答案无关)

SELECT CONCAT_WS(',',tmp1.rid, tmp2.rid) AS rid
FROM mybb_reputation AS tmp1
JOIN mybb_reputation AS tmp2
  ON tmp1.rid < tmp2.rid
WHERE tmp1.reputation + tmp2.reputation = 3

查找任何3条记录(与之前相同的想法&lt;)

SELECT CONCAT_WS(',',tmp1.rid, tmp2.rid, tmp3.rid) AS rid
FROM mybb_reputation AS tmp1
JOIN mybb_reputation AS tmp2
  ON tmp1.rid < tmp2.rid
JOIN mybb_reputation AS tmp3
  ON tmp2.rid < tmp3.rid
WHERE tmp1.reputation + tmp2.reputation + tmp3.reputation = 3

查找4(算法重复)

SELECT CONCAT_WS(',',tmp1.rid, tmp2.rid, tmp3.rid, tmp4.rid) AS rid
FROM mybb_reputation AS tmp1
JOIN mybb_reputation AS tmp2
  ON tmp1.rid < tmp2.rid
JOIN mybb_reputation AS tmp3
  ON tmp2.rid < tmp3.rid
JOIN mybb_reputation AS tmp4
  ON tmp3.rid < tmp4.rid
WHERE tmp1.reputation + tmp2.reputation + tmp3.reputation + tmp4.reputation = 3

您需要为所需的许多组合继续此操作。

答案 1 :(得分:0)

SELECT *
FROM mybb_reputation
GROUP BY uid
HAVING SUM(reputation) >= 3
ORDER BY RAND()
LIMIT 1

不确定这个的确切顺序,但它应该包含您需要的所有条件。

老实说,你的数据结构似乎很奇怪,无法回答这些问题。

答案 2 :(得分:0)

您可能希望获得组的总和。我打算假设你想通过uid分组:

SELECT * FROM mybb_reputation 
WHERE uid in 
  (Select uid FROM mybb_reputation
   GROUP BY uid
   HAVING SUM(reputation) = 3);

如果要选择与某些聚合条件匹配的各个行,则需要子查询。嵌套子查询查找具有所需条件的组。然后外部查询说返回该组中的每一行。必须以某种方式识别该组,在这种情况下,我们使用uid。

MySQL的某些实现会将此视为相关子查询,如果您的表很大,这可能是一个问题。如果您遇到此问题,可以再添加一个subselect图层来修复它:

SELECT * FROM mybb_reputation 
WHERE uid in 
  (SELECT * FROM
     (Select uid FROM mybb_reputation
      GROUP BY uid
      HAVING SUM(reputation) = 3));

或使用连接而不是子查询:

SELECT r1.* FROM mybb_reputation r1,
     (Select uid FROM mybb_reputation
      GROUP BY uid
      HAVING SUM(reputation) = 3) r2
WHERE r1.uid = r2.uid;

答案 3 :(得分:0)

试试这个

SELECT * FROM mybb_reputation GROUP BY rid HAVING SUM(reputation) = 3 ORDER BY RAND() LIMIT 1;