mysql - 关于子查询配对结果的建议

标签 mysql sql

我有一个包含两列的数据表,user_id 和 preference_id。我正在努力弄清楚如何返回共享 preference_id 的 user_id 对,以及任何成对偏好的计数。

我知道这将是一个子查询问题,首先找到具有 preference_id 的 user_id,然后(在子查询中)再次检查数据库以查找具有相同 preference_id 的新 user_id(以及谁不是第一个用户)。我不知道如何构建查询。

因为我想返回两个不同的 user_id,所以我的子查询应该放在选择部分是否合乎逻辑?

--- 编辑:

表格的一个例子是:

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;

关于mysql - 关于子查询配对结果的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53479491/

相关文章:

mysql - 如何将mysql数据库提取为.mdf

sql - 普通表表达式,遍历图时如何避免无限递归?

java - 将结果集值放入 Collection 对象,然后添加到 ArrayList

php - 在 mysql 中添加一列,以便根据登录的用户转到特定页面

php - 运行多个 SELECT、INSERT INTO 和 DELETE

python - 如何使用 Python 处理 SQL 转储

php - 下拉数据不发布 "The forum you are trying to create a topic on, does not exist!"

mysql - 日志表的查询优化

mysql - 添加表中每一行的值并输出(将 JSON 字符串转换为 int)

mysql - 留言板结构数据库