将变量传递给嵌套查询

时间:2011-09-01 18:36:06

标签: mysql

假设用户表有200条记录。

以下查询适用于某个 worker_id 例如worker_id 2738:

SELECT SUM(something) AS T_BOIN
FROM (
SELECT SUM(A.boin) AS something 
FROM hall A JOIN user B ON A.who=B.id 
WHERE B.worker_id = 2738
ORDER BY total_per_user DESC LIMIT 10
) AS mastertbl

我想对200个单独的worker_ids执行上述查询,如下所示:

SELECT @TT:=BK.worker_id AS TID, 
 (SELECT SUM(something) AS T_BOIN
 FROM (
  SELECT SUM(A.boin) AS something
  FROM hall A
  JOIN user B ON A.who=B.id
  WHERE B.worker_id = @TT
  ORDER BY total_per_user DESC 
  LIMIT 10) AS mastertbl
 ) AS TEAM
FROM user BK
INNER JOIN (SELECT @TT :=0) AS WESS
GROUP BY TID

但@tt超出了范围。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为这对你有用......

SELECT worker_id, SUM(something) AS T_BOIN
FROM (
  SELECT b.worker_id, SUM(A.boin) AS something, if(@wid = b.worker_id, @cnt:=@cnt+1, @cnt:=1 AND @wid := b.worker_id) cnt
  FROM hall A
  JOIN user B ON A.who=B.id 
  ORDER BY b.worker_id, total_per_user DESC
) AS mastertbl
WHERE mastertbl.cnt <= 10
GROUP BY worker_id;