MYSQL sum of item purchases and its 'up'/'down' 票数乘以22?

标签 mysql select join sum

我正在尝试计算与给定搜索词匹配的所有项目的购买次数和“赞成”/“反对”票数。不幸的是,当我现在设置我的查询时,购买和投票计数乘以一个神秘的因子 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/

相关文章:

mysql - mysql select中的缩写,它们是什么意思?

sql连接或多选?

php - Codeigniter Active Record/MySQL 连接查询 - 如果其中一个表行不存在,如何返回结果

mysql - 如何使用mysql从一组id中搜索一个id?

mysql - SQL中如何删除字符串中的多个字符

mysql - 使用 inner join 时 Sum 的条件?

mysql - 左连接后更新行

mysql - 如何解决MySQL死锁

mysql存储过程,使用列名作为参数

javascript - 如何使用更改事件返回 meteor 中选定选项值的 ID?