這應該做你想要什麼:
SELECT object.name, COUNT(*) AS tag_count
FROM tagset T1
JOIN tagset T2
ON T1.tag_id = T2.tag_id AND T1.object_id != T2.object_id
JOIN object
ON T2.object_id = object.id
WHERE T1.object_id = 1
GROUP BY T2.object_id
ORDER BY COUNT(*) DESC
結果:
'object2', 2
'object3', 1
使用這個測試數據:
CREATE TABLE object (id int NOT NULL, name nvarchar(100) NOT NULL);
INSERT INTO object (id, name) VALUES
(1, 'object1'),
(2, 'object2'),
(3, 'object3');
CREATE TABLE tagset (object_id int NOT NULL, tag_id int NOT NULL);
INSERT INTO tagset (object_id, tag_id) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 1),
(2, 3),
(3, 2),
(3, 4),
(3, 5);
我假設你不想將對象本身包含在結果集中? – 2010-01-26 22:09:13