Mysql 关于子查询的成对结果的建议
我有一个数据表,其中有两列,user_id和preference_id。我正在努力找出如何返回共享preference_id的用户_id对,以及任何成对首选项的计数 我认识到这将是一个子查询问题,首先查找具有首选项id的用户id,然后在子查询中再次检查数据库,查找具有相同首选项id且不是第一个用户的新用户id。我不知道如何构造查询 我的子查询应该在select部分,因为我想返回两个不同的用户ID,这看起来合乎逻辑吗 --编辑: 该表的一个示例是:Mysql 关于子查询的成对结果的建议,mysql,sql,Mysql,Sql,我有一个数据表,其中有两列,user_id和preference_id。我正在努力找出如何返回共享preference_id的用户_id对,以及任何成对首选项的计数 我认识到这将是一个子查询问题,首先查找具有首选项id的用户id,然后在子查询中再次检查数据库,查找具有相同首选项id且不是第一个用户的新用户id。我不知道如何构造查询 我的子查询应该在select部分,因为我想返回两个不同的用户ID,这看起来合乎逻辑吗 --编辑: 该表的一个示例是: DROP TABLE IF EXISTS `pe
DROP TABLE IF EXISTS `people_preferences`;
CREATE TABLE `people_preferences`
(
`personid` int(11),
`preferenceid` int(11)
);
INSERT INTO `people_preferences` VALUES (1,10),(1,24),(1,38),(2,1),(2,10),(2,38),(3,5),(3,38);
我相信我需要的东西大致如下:
select people_preferences.personid,
(select people_preferences.personid where....)
from people_preferences
where people_preferences.personid <> people_preferences.personid;
但很明显,这是行不通的,因为最终的声明不会做任何明智的事情。如果我理解正确,您需要成对的用户和计数。如果是:
select pp1.personid, pp2.personid,
count(*) as num_preferences_in_common
from people_preferences pp1 join
people_preferences pp2
on pp1.preferenceid = pp2.preferenceid and
pp1.personid < pp2.personid -- only need pairs of people in one direction
group by pp1.personid, pp2.personid
order by num_preferences_in_common;
如果我理解正确,您需要成对的用户和计数。如果是:
select pp1.personid, pp2.personid,
count(*) as num_preferences_in_common
from people_preferences pp1 join
people_preferences pp2
on pp1.preferenceid = pp2.preferenceid and
pp1.personid < pp2.personid -- only need pairs of people in one direction
group by pp1.personid, pp2.personid
order by num_preferences_in_common;
如果你能分享一些数据、样本输入和预期输出,那就太好了。请阅读此链接:抱歉,我在帖子中包含了一个我的意思示例。如果你能分享一些数据、样本输入和预期输出,那就太好了。请阅读此链接:抱歉,我在帖子中包含了一个我的意思示例。谢谢。这对我来说是新鲜事,我以前从未看过《开》。谢谢。这对我来说是新鲜事,我以前从来没有看过《开》。