mysql - 给定一个用户,选择具有最常见评分的用户

标签 mysql sql

假设我有一个评级表:

create table ratings (
    user_id int unsigned not null,
    post_id int unsigned not null,
    rating set('like', 'dislike') not null,
    primary key (user_id, post_id)
);

对于id 1的给定用户,我如何选择具有更多共同喜欢的用户?不喜欢的用户有哪些共同点?具有更多评分(喜欢或不喜欢)的用户有什么共同点?我想这些查询会非常相似,但我还无法弄清楚其中的任何一个。我将更新我取得的任何进展。

感谢任何帮助,谢谢!

最佳答案

select
    r1.user_id as user1
    ,r2.user_id as user2
    ,r1.rating as rating
    ,count(*) as num_matching_ratings
from
    ratings r1 
    inner join ratings r2
        on r1.post_id = r2.post_id 
            and r1.rating = r2.rating
            and r1.user_id <> r2.user_id --don't want to count
                                         --matches with self
where
    r1.user_id = 1 -- change this to any user, or use a
                   -- variable to increase reusebility
    and r1.rating = 'like' -- set this to dislike to common dislikes
group by
    r1.user_id
    ,r2.user_id
    ,r1.rating
having
    count(*) > 1 --show only those with more than 1 in common
order by
    count(*) desc
/* limit 1 -- uncomment to show just the top match */

通过将表连接在一起,我们可以计算第二个用户对文章进行类似评分的次数。此查询将返回从最常见到最不常见的评估。如果取消注释“limit 1”语句,它将仅返回最常见的匹配项。

关于mysql - 给定一个用户,选择具有最常见评分的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708702/

相关文章:

mysql - mysql存储过程中的错误日期值错误

java - XML 解析为 SQL 代码

mysql - 在插入时更改另一个表中的另一个列值

sql - 如何在 Amazon Redshift 中选择多个填充常量的行?

mysql - 分组以避免在其中一个值发生更改的行之间返回具有相同列值集的行

mysql - ON DUPLICATE KEY UPDATE 不起作用

sql - 3 表计数查询mysql

mysql - 如何查询 Eloquent ORM 多对多关系

mysql - 从mysql迁移到Couchbase。这是个好主意吗?

sql - 自动生成与现有表匹配的用户定义表类型