SELECT *, SUM(CASE WHEN "token"."name" = '' THEN 5 ELSE 9 END) AS "n"
FROM "word"
LEFT OUTER JOIN "token" ON ("word"."id" = "token"."word_id")
where ("word"."id" = 1)
GROUP BY "word"."id";
这给出了14的预期结果,因为只有一个空标记和一个非空标记。
SELECT *, SUM(CASE WHEN "token"."name" = '' THEN 5 ELSE 9 END) AS "n"
FROM "word"
LEFT OUTER JOIN "token" ON ("word"."id" = "token"."word_id")
INNER JOIN "token" T3 ON ("word"."id" = T3."word_id")
where ("word"."id" = 1)
GROUP BY "word"."id";
此查询输出n=28
,这是14加倍。
为什么?
答案 0 :(得分:0)
这是您修改过的查询:
SELECT *, SUM(CASE WHEN t."name" = '' THEN 5 ELSE 9 END) AS "n"
FROM "word" w LEFT OUTER JOIN
"token" t
ON w."id" = t."word_id" INNER JOIN
"token" T3
ON w."id" = T3."word_id"
WHERE w."id" = 1
GROUP BY w."id";
没有意义。您将word
中的同一列加入token
中的同一列 - 两次。您获得重复的原因是因为您在token
中有多个行用于给定的单词。您可以轻松查看:
select word_id, count(*)
from token
group by word_id
having count(*) > 1;
但是,您的查询毫无意义。我可能会建议您使用示例数据,所需结果以及您希望查询执行操作的说明来询问另一个问题。