mysql - 计算mysql表的有限行数之和?

标签 mysql subquery

我正在使用 drupal website ,并且我想显示有限数量的术语。但我失败了,在运行查询时,我将查询简化为询问。

我想计算mySQL表的有限行的总和,但不幸的是,mySQL上升了Unknown column “where 子句”中的“node.node_id”错误。

查询 PostgreSQL (SQLFiddle) 的工作。 我有以下架构

create table rating (
  node_id int,
  rank int
);

create table node (
  node_id int
);

insert into node
(node_id)
values
(1),
(2);

insert into rating
(node_id, rank)
values
(1, 2),
(1, 3),
(1, 5),
(1, 7),
(2, 5),
(2, 7),
(2, 11),
(2, 13)
;

我的查询是

select node.node_id, (
  select sum(rank)
  from (
    select child_rating.rank
    from rating as child_rating
    where child_rating.node_id = node.node_id
    limit 3
  ) as _child

) as sum
from node

参见SQLFiddle以获得预期结果。 (或者参见下图以了解预期结果 SQLFiddle

enter image description here

我想知道是否有人可以帮助我。谢谢

最佳答案

在 MySQL 中,根据每个组限制记录总是很棘手。

下面的sql查询为您提供了解决方案:

select node_id, sum(rank) from (
SELECT @row_number:=CASE WHEN @node_id=node_id 
THEN @row_number+1 ELSE 1 END AS row_num,@node_id:=node_id AS node_id, rank
FROM rating, (SELECT @row_number:=0,@node_id:='') AS t
  ORDER BY node_id
  )t1
where row_num <= 3
group by node_id
;

SQL fiddle 链接:http://sqlfiddle.com/#!2/b142f/5

P.S:请查看以下链接,我几天前已在其中回答过。 auto increment by specific column's data

关于mysql - 计算mysql表的有限行数之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26836928/

相关文章:

mySQL:子查询到数组?

php - 我可以在子查询中使用全文mysql查询吗

c# - Nhibernate DetachedCriteria Left Outer Join 子查询

php - Select item in join table 每个链接需要满足多组条件

php - 在 PHP 中获取 mySQL 数据库中的最大数字

php - 使用 PHP 将 CSV 文件数据插入和更新到 MySQL 表中

mysql - 如何让子删除查询更快?

mysql - 子查询的问题

mysql - 如何使用 codeigniter 在 View 中显示来自多个表的数据

php - INSERT INTO 后立即使用 AI 获取 PK 列