我正在尝试计算与给定搜索词匹配的所有项目的购买次数和“赞成”/“反对”票数。不幸的是,当我现在设置我的查询时,购买和投票计数乘以一个神秘的因子 22,我无法弄清楚它来自哪里。
作为其中一项的示例:购买、赞成票和反对票应分别为 7、2 和 1,但它们分别为 154、44 和 22。
这是我的 SQL 代码:
SELECT *
sum(purchaseyesno) as tots,
sum(rating=1) as yes,
sum(rating=0) as no
from items
join items_purchased
on items_purchased.item_id=items.item_id
join accounts
on items.account_id=accounts.account_id
like subject='%album by joe%' or description='%album by joe%'
group by item_id
order by tots desc, yes desc
这是一些示例数据:
subject tots yes no full_name
album by joe 154 44 22 joe smith
album by fred 88 44 0 fred jones
这是我希望数据的样子:
subject tots yes no full_name
album by joe 7 2 1 joe smith
album by fred 4 2 0 fred jones
有人能帮我弄清楚这里发生了什么吗?尽管更改了 group by
和其他内容(意思是,这个 22 数字与返回行的数量无关),但我无法弄清楚这个问题仍然存在的 22 因素。
最佳答案
您没有显示您的架构,但使用子查询可能会有所帮助:
SELECT subject, tots, yes, no, fullnane
FROM (
SELECT item_id, SUM(purchaseyesno) AS tots, SUM(rating=1) AS yes, SUM(rating=0) AS no
FROM items_purchased
GROUP BY item_id
) i
JOIN items ON i.item_id = items.item_id
JOIN accounts ON items.account_id=accounts.account_id
WHERE subject LIKE '%album by joe%' OR description LIKE '%album by joe%'
ORDER BY tots DESC, yes DESC
关于MYSQL sum of item purchases and its 'up'/'down' 票数乘以22?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9967807/