我有一个数据表,其中有两列user_id和preference_id。我正在努力弄清楚如何返回共享有preference_id的user_id对,以及任何成对的偏好的计数。
我知道这将是一个子查询问题,首先要找到一个带有preference_id的user_id,然后(在子查询中)再次在数据库中检查一个具有相同preference_id(又不是第一个用户)的新user_id。我不知道该如何构造查询。
因为我想返回两个不同的user_id,所以子查询应该在select部分中看起来合乎逻辑吗?
---编辑:
该表的示例为:
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;
但是很明显,这是行不通的,因为最终声明不会做任何明智的事情。
答案 0 :(得分:4)
如果我的理解正确,那么您需要一对用户和一个计数。如果是这样:
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;