-1

这是 mybb_reputation 表

mybb_reputation 表

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

我试过运行这个查询;

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

但由于 MySQL 知识有限,它显示错误,例如:#1111 - 组函数的无效使用

请帮忙!

4

4 回答 4

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 条记录(与之前关于 < 的想法相同)

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

无论您想要多少组合,您都需要继续此操作。

于 2013-10-12T17:04:19.577 回答
0
SELECT *
FROM mybb_reputation
GROUP BY uid
HAVING SUM(reputation) >= 3
ORDER BY RAND()
LIMIT 1

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

老实说,您的数据结构在回答此类查询时似乎很奇怪。

于 2013-10-12T15:55:11.043 回答
0

您可能希望获得一个组的总和。我假设你想按 uid 分组:

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

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

MySQL 的一些实现会将其视为相关子查询,如果您的表很大,这可能是一个问题。如果你有这个问题,你可以再添加一层子选择来修复它:

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;
于 2013-10-12T15:59:41.527 回答
0

试试这个

SELECT * FROM mybb_reputation GROUP BY rid HAVING SUM(reputation) = 3 ORDER BY RAND() LIMIT 1;
于 2013-10-12T16:00:38.927 回答