我有3个表:用户,投票和歌曲。
歌曲包含歌曲详细信息 投票包含歌曲ID,投票的用户和投票值 用户包含用户详细信息
当用户对歌曲进行投票时,他们的投票将被存储。要么是1还是0.每首歌都有一种类型,每次投票都可以识别。
我想做的是这样......
Pop 1
Rock 3
Reggie 4
Vote percent is the total amount of 1s received so 1, 3, 4.
These as a % is my aim so Reggie would be 50%. (8/4) and so on...
I then want to use this list of prefered genres to pick songs based on the % values.
因此,如果有任何Reggie歌曲,这将首先在列表中返回。
SELECT s.* FROM song s
WHERE (
SELECT 100.00 * SUM(CASE WHEN vote = '1' THEN 1 WHEN vote = '2' THEN 0.5
ELSE 0 END) / COUNT(v.vote) AS votePercent
FROM song s
LEFT JOIN collaborate c
ON s.song_id = c.song_id
LEFT JOIN voting v
ON s.song_id = v.song_id
WHERE v.user_id = 'user0d1c-944f-4fff-b819-16869750f2d4'
)
GROUP BY s.genre;
到目前为止,我所尝试的内容似乎不同,因为百分比值的类型为100%和50%,而不是总票数的百分比。
此外,我当前的查询几乎肯定会返回已经投票的歌曲。
我走错了方向,还是对我希望实现的目标抱有一些承诺?
答案 0 :(得分:0)
我认为问题出在您的group by
,当您获得COUNT(v.vote)
时,它就是分组计数,而不是总计数。
试试这个:
SELECT s.* FROM song s
WHERE (
SELECT 100.00 * SUM(CASE WHEN vote = '1' THEN 1 WHEN vote = '2' THEN 0.5
ELSE 0 END) / (SELECT COUNT(*) FROM voting) AS votePercent
FROM song s
LEFT JOIN collaborate c
ON s.song_id = c.song_id
LEFT JOIN voting v
ON s.song_id = v.song_id
WHERE v.user_id = 'user0d1c-944f-4fff-b819-16869750f2d4'
)
GROUP BY s.genre;
然后可能出现的问题是count和sum都是整数,所以mysql可能会从结果中删除小数值。
要解决此问题,我们可以将SUM转换为小数:
SELECT s.* FROM song s
WHERE (
SELECT 100.00 * CAST(SUM(CASE WHEN vote = '1' THEN 1 WHEN vote = '2' THEN 0.5
ELSE 0 END) as DECIMAL(10,2) / (SELECT COUNT(*) FROM voting) AS votePercent
FROM song s
LEFT JOIN collaborate c
ON s.song_id = c.song_id
LEFT JOIN voting v
ON s.song_id = v.song_id
WHERE v.user_id = 'user0d1c-944f-4fff-b819-16869750f2d4'
)
GROUP BY s.genre;
这是未经测试的,但我认为它可能会指向正确的方向。