添加到 WITH RECURSIVE 查询中的变量 MySQL

add to variable in WITH RECURSIVE query MySQL

基本上我想创建一个变量,然后为我的查询搜索的每一行增加 "votes" int 的值。

可能吗?

像这样:

set @tally=0;

WITH RECURSIVE descendants AS
(
SELECT id
FROM ballots
WHERE parent=0
UNION ALL
SELECT t.id
FROM descendants d, ballots t
WHERE t.parent=d.id

@tally+=SELECT voteCount FROM descendants d, ballots t WHERE t.parent=d.id
)
SELECT * FROM descendants;
SELECT @tally;



想通了。我采取了错误的方法。无需将每个单独的值相加,您只需获得搜索结束时返回的所有内容的总和。

SET @tally=0;
WITH RECURSIVE descendants AS
(
SELECT id, votes
FROM ballots
WHERE parent=0
UNION ALL
SELECT t.id, t.votes
FROM descendants d, ballots t
WHERE t.parent=d.id
)
SELECT sum(votes) INTO @tally FROM descendants;
SELECT @tally;