我有一个存储用户兴趣的数据库表:
CREATE TABLE `ade39_findme_settings_words` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`word` varchar(255) DEFAULT NULL,
`language` varchar(2) DEFAULT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `clickeditem` (`user_id`),
KEY `count` (`word`)
) ENGINE=MyISAM AUTO_INCREMENT=134 DEFAULT CHARSET=utf8;
word = interest
现在我想在此表中搜索具有一个或多个相同兴趣的用户,并按相同兴趣的数量对此列表进行排序。知道sql查询的样子吗?
喜欢“与user_id = 62具有相似兴趣的所有用户”
示例:
USER INTEREST
62 riding
62 reading
62 dancing
75 riding
75 dancing
80 riding
输出:
USER SAME_COUNT
75 2
80 1
感谢。
答案 0 :(得分:1)
您可能遇到性能问题,因此您可以尝试使用EXISTS
进行改进SELECT t.user_id, COUNT(*) as num_interests, GROUP_CONCAT(word) as interests
FROM ade39_findme_settings_words t
WHERE EXISTS
( SELECT 1
FROM ade39_findme_settings_words t1
WHERE t1.user_id = 62
AND t1.word = t.word
)
AND user_id <> 62
GROUP BY t.user_id
ORDER BY num_interests DESC;
最快的方法是使用排除JOIN,但是这样
SELECT t.user_id, COUNT(*) as num_interests, GROUP_CONCAT(t.word) as interests
FROM ade39_findme_settings_words t
LEFT JOIN ade39_findme_settings_words t1 ON t1.user_id = 62 AND t1.word = t.word
WHERE t.user_id <> 62
GROUP BY user_id
ORDER BY num_interests DESC;
答案 1 :(得分:0)
SELECT `user_id`, COUNT(*) as same_count
FROM `ade39_findme_settings_words`
WHERE `word` IN (SELECT `word` FROM `ade39_findme_settings_words` WHERE `user_id` = 62)
GROUP BY `user_id`
ORDER BY same_count DESC;
答案 2 :(得分:0)
这对我也很有用:
select temp.id_new , count(temp.intrst)
from
(select a.user_id id_new, a.word intrst
from ade39_findme_settings_words a
where a.word in (select b.word from ade39_findme_settings_words b where b.user_id=62)
and a.user_id<>62 ) temp
group by temp.id_new;