gpt4 book ai didi

MySQL组通过影响其他组

转载 作者:行者123 更新时间:2023-11-29 02:27:44 24 4
gpt4 key购买 nike

我有一个 SUM(value) 计算每个 idea 的投票数,但这会受到 tag 数量的影响每个想法都可以有。

例如,

SELECT 
id,
title,
description,
COALESCE(SUM(case when value > 0 then value end),0) votes_up,
COALESCE(SUM(case when value < 0 then value end),0) votes_down,
GROUP_CONCAT(DISTINCT tags.name) AS 'tags',
FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
LEFT JOIN tags_rel ON ideas.id = tags_rel.idea_id
LEFT JOIN tags ON tags_rel.tag_id = tags.id
GROUP BY ideas.id

因此,如果有多个 tags.name,则 SUM() 会乘以 tags.name 的数量>/p>

我该如何解决这个问题?

最佳答案

如果您不希望您的 SUM 受到 tags 的影响,则不应将 include tags 到您的SUM 查询。

我认为您可以将查询分成两部分(query inside a query)。首先对 没有 ideas 求和,然后根据第一部分的结果 JOIN ideas 数据

想要的东西(抱歉,我还没有测试我的查询,但想法是这样的):

SELECT 
t.id,
t.title,
t.description,
t.votes_up,
t.votes_down,
GROUP_CONCAT(DISTINCT tags.name) AS 'tags',

FROM
(
SELECT
id,
title,
description,
COALESCE(SUM(case when value > 0 then value end),0) votes_up,
COALESCE(SUM(case when value < 0 then value end),0) votes_down,
FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
GROUP BY ideas.id
) as t
LEFT JOIN tags_rel ON t.id = tags_rel.idea_id
LEFT JOIN tags ON tags_rel.tag_id = tags.id

希望对你有帮助

关于MySQL组通过影响其他组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com