如果可能的话,如果可能的话,我可以通过表格中给定用户和每个其他用户之间的匹配数来“得分”结果。
基本上,我有一个'1'的'userid',我需要根据用户兴趣和订单检查所有这些用户的兴趣,以及用户之间匹配的数量。
假设userid'1'与userid'4'有4个共同兴趣,但只有3个与userid'2'共同的兴趣,它将首先返回4,然后是2,然后整体兴趣较少的其他所有人匹配。< / p>
我已经尝试了大约10个不同的查询无效,甚至没有一个接近,这就是为什么我没有在这里发布任何尝试。
CREATE TABLE `interests` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`userid` int(12) NOT NULL DEFAULT '0',
`interest` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `interests` set `userid` = '1', `interest` = 'term1';
INSERT INTO `interests` set `userid` = '1', `interest` = 'term2';
INSERT INTO `interests` set `userid` = '1', `interest` = 'term3';
INSERT INTO `interests` set `userid` = '1', `interest` = 'term4';
INSERT INTO `interests` set `userid` = '2', `interest` = 'term1';
INSERT INTO `interests` set `userid` = '2', `interest` = 'term2';
INSERT INTO `interests` set `userid` = '2', `interest` = 'term8';
INSERT INTO `interests` set `userid` = '2', `interest` = 'term4';
INSERT INTO `interests` set `userid` = '3', `interest` = 'term9';
INSERT INTO `interests` set `userid` = '3', `interest` = 'term2';
INSERT INTO `interests` set `userid` = '3', `interest` = 'term3';
INSERT INTO `interests` set `userid` = '3', `interest` = 'term7';
INSERT INTO `interests` set `userid` = '4', `interest` = 'term1';
INSERT INTO `interests` set `userid` = '4', `interest` = 'term2';
INSERT INTO `interests` set `userid` = '4', `interest` = 'term3';
INSERT INTO `interests` set `userid` = '4', `interest` = 'term4';
正确的结果集应如下所示:
-------
userid
-------
4
2
3
非常感谢大家的帮助。
答案 0 :(得分:1)
您可以执行SELF JOIN
:
SELECT i2.userid
FROM interests i1
INNER JOIN interests i2
ON i2.userid <> i1.userid
AND i2.interest = i1.interest
WHERE i1.userid = 1
GROUP BY i2.userid
ORDER BY COUNT(*) DESC;
答案 1 :(得分:1)
最简单的方法是获取所有用户和共享和计数的列表,然后从该子查询中选择和排序所需的用户。它使逻辑清晰:
SELECT userid, otherid, sameCount
FROM (
SELECT base.userid, other.userid as otherid, count(*) sameCount
FROM interests base
JOIN interests other ON base.interest = other.interest and base.userid != other.userid
GROUP BY base.userid, other.userid
) sub
WHERE userid = 1
ORDER BY sameCount DESC
答案 2 :(得分:0)
此查询应该这样做
select i.userid, count(i2.userid) countInterests
from interests i
inner join interests i2 on i.interest = i2.interest and i.Id <> i2.id
group by i.userid, i2.userid
order by userid, count(i2.userid) desc