我現在有一個查詢,可以正確拉取不同用戶之間給定起始用戶標識符的評分匹配。在執行主查詢之前,如何優化查詢以首先在另一個表上執行檢查?
SELECT i2.userid
FROM users_interests i1
INNER JOIN users_interests i2
ON i2.userid <> i1.userid
AND i2.interest = i1.interest
WHERE i1.userid = 1
GROUP BY i2.userid
ORDER BY COUNT(*) DESC
LIMIT 0,10;
我怎樣才能適應這一點很容易,首先爲用戶做的正確的國家檢查在不同的users
表,運行興趣匹配查詢之前,使其只有當他們在適當的國家運行的匹配查詢?
起始userid
應該是 '1',和適當的country
應該是 '1'
正確返回的結果集應該是:
-------
userid
-------
3
樣品測試數據
CREATE TABLE `users` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`country` int(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `users` SET `id` = '1', `country` = '1';
INSERT INTO `users` SET `id` = '2', `country` = '2';
INSERT INTO `users` SET `id` = '3', `country` = '1';
INSERT INTO `users` SET `id` = '4', `country` = '4';
CREATE TABLE `users_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 `users_interests` set `userid` = '1', `interest` = 'term1';
INSERT INTO `users_interests` set `userid` = '1', `interest` = 'term2';
INSERT INTO `users_interests` set `userid` = '1', `interest` = 'term3';
INSERT INTO `users_interests` set `userid` = '1', `interest` = 'term4';
INSERT INTO `users_interests` set `userid` = '2', `interest` = 'term1';
INSERT INTO `users_interests` set `userid` = '2', `interest` = 'term2';
INSERT INTO `users_interests` set `userid` = '2', `interest` = 'term8';
INSERT INTO `users_interests` set `userid` = '2', `interest` = 'term4';
INSERT INTO `users_interests` set `userid` = '3', `interest` = 'term9';
INSERT INTO `users_interests` set `userid` = '3', `interest` = 'term2';
INSERT INTO `users_interests` set `userid` = '3', `interest` = 'term3';
INSERT INTO `users_interests` set `userid` = '3', `interest` = 'term7';
INSERT INTO `users_interests` set `userid` = '4', `interest` = 'term1';
INSERT INTO `users_interests` set `userid` = '4', `interest` = 'term2';
INSERT INTO `users_interests` set `userid` = '4', `interest` = 'term3';
INSERT INTO `users_interests` set `userid` = '4', `interest` = 'term4';
爲什麼你期望'1'能成爲結果嗎?它與起始用戶標識相同,並限制'i2.userid <> i1.userid' – Misha
你是對的,brainfart,更新問題。 –