Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 给定一个用户,选择具有最常见评级的用户_Mysql_Sql - Fatal编程技术网

Mysql 给定一个用户,选择具有最常见评级的用户

Mysql 给定一个用户,选择具有最常见评级的用户,mysql,sql,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的给定用户,我如何选择具有更多共同爱好的用户?与用户有更多共同的不喜欢?与评分较高的用户有共同的好恶?我猜这些问题

假设我有一个评级表:

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的给定用户,我如何选择具有更多共同爱好的用户?与用户有更多共同的不喜欢?与评分较高的用户有共同的好恶?我猜这些问题会非常相似,但我还不能找出其中任何一个。我会更新我取得的任何进展


感谢您的帮助,谢谢

请原谅我的语法,我不经常编写原始sql。你可以考虑这个密码。< /P> 首先,我得到id为1的表

view1=从分级中选择*,其中用户id=1

然后我会加入评级

view2=从view1、ratings中选择*,其中view1.rating=ratings.rating和view1.post_id=records.post_id

然后我会数一数

view3=按用户id从view2组中选择计数

然后我就可以尽情享受了

现在,这只是我最初想法的算法概述。我认为它不会特别有效,而且您可能不会使用这种语法

试试看:

select r2.user_id from (
  select post_id, rating from ratings,
    (select @userId := 2) init
  where user_id = @userId
) as r1
join ratings r2
on r1.post_id = r2.post_id and r1.rating = r2.rating
where r2.user_id != @userId and r2.rating = 'like'
group by r2.user_id
order by count(*) desc
limit 1
它应该通过更改字符串来表示喜欢和不喜欢。要更改用户,只需修改变量分配

仅通过删除过滤条件,以下内容就可以同时适用于不喜欢和喜欢:

select r2.user_id from (
  select post_id, rating from ratings,
    (select @userId := 2) init
  where user_id = @userId
) as r1
join ratings r2
on r1.post_id = r2.post_id and r1.rating = r2.rating
where r2.user_id != @userId
group by r2.user_id
order by count(*) desc
limit 1

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

基于Chris和Mostacho的答案,我提出了以下查询。我不是100%确定它每次都能工作,但我还没有发现任何缺陷

select r2.user_id
from ratings r1
join ratings r2
on r1.user_id <> r2.user_id
and r1.post_id = r2.post_id 
and r1.rating = r2.rating
where r1.user_id = 1 
and r1.rating = 'like'
group by r2.user_id
order by count(r2.user_id) desc
limit 1

此查询返回与用户1有更多共同喜好的用户的id。要获取具有更常见评级的用户,只需从where子句中删除和r1.rating='like'。

对不起,删除其评论的人指出我的算法存在问题。后来我做了一个更正,我最终对您的查询进行了修改,我会将其作为不同的答案发布。我认为查询中唯一的缺陷是顺序应该是countr2.user\u id,我不理解为什么需要按三列进行分组,我认为按r2.user\u id进行分组就足够了。
select r2.user_id
from ratings r1
join ratings r2
on r1.user_id <> r2.user_id
and r1.post_id = r2.post_id 
and r1.rating = r2.rating
where r1.user_id = 1 
and r1.rating = 'like'
group by r2.user_id
order by count(r2.user_id) desc
limit 1