事情是這樣的:
SELECT first_user.id_user, second_user.id_user, COUNT(first_user.id_user) AS total_matches
FROM likes AS first_user
JOIN likes AS second_user
ON second_user.id_artist = first_user.id_artist
AND second_user.id_user != first_user.id_user
GROUP BY first_user.id_user, second_user.id_user
ORDER BY total_matches DESC
LIMIT 1
注意,這不是很有效。解決此問題的一種方法是創建一個包含此查詢輸出的「緩存表」,並刪除LIMIT 1
部分。添加一些相關索引並查詢此緩存表。您可以設置一個cron作業來定期更新此表。
實施例:
CREATE TABLE IF NOT EXISTS `likes` (
`id_user` varchar(50) DEFAULT NULL,
`id_artist` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `likes` (`id_user`, `id_artist`) VALUES ('8', '39'), ('8', '37'), ('4', '37'), ('8', '24'), ('8', '7'), ('4', '28'), ('8', '28'), ('4', '27'), ('4', '11'), ('8', '49'), ('4', '7'), ('4', '40'), ('4', '29'), ('8', '22'), ('4', '29'), ('8', '11'), ('8', '28'), ('4', '7'), ('4', '31'), ('8', '42'), ('8', '25'), ('4', '25'), ('4', '17'), ('4', '32'), ('4', '46'), ('4', '19'), ('8', '34'), ('3', '32'), ('4', '21')
+---------+---------+---------------+
| id_user | id_user | total_matches |
+---------+---------+---------------+
| 8 | 4 | 7 |
+---------+---------+---------------+
感謝您的幫助,您的查詢就像一個chram :) – MonsieurNinja
@sikko高興地幫助!與你的項目祝你好運:) –