在显示特定对象的页面上,我需要根据标记显示该对象的相关对象。 '具有最多匹配标记的对象应位于顶部。基本上我需要确定每个对象与页面上的对象匹配的标签数量,并显示最佳结果。
我的数据库架构:
Table Object
------------
id
name
Table Tagset
-------------
object_id
tag_id
Table Tag
------------
id
name
答案 0 :(得分:2)
这应该做你想要的:
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);
答案 1 :(得分:1)
显然未经测试,但它应该起作用或至少让你走上正确的轨道:
SELECT ts.object_id, o.name, COUNT(ts.*) as matching_tags
FROM Tagset ts
INNER JOIN
(SELECT tag_id
FROM Tagset
WHERE object_id = <your object id>) otags ON ts.tag_id = otags.tag_id
INNER JOIN Object o ON ts.object_id = o.id
WHERE ts.object_id <> <your object id>
GROUP BY ts.object_id, o.name
ORDER BY COUNT(ts.*)
基本上我们首先创建一个select语句,它将获取您的对象所属的所有标记,然后我们将其用作派生表并加入它以过滤掉外部select中的任何其他标记。最后,我们对object_id进行分组,并在tagset表上执行COUNT(*)以找出许多匹配的标记。
编辑:忘记了外面的where子句来摆脱你的源对象。答案 2 :(得分:0)
select t.id, t.name
from tag t
inner join
(
select tag_id, count(tag_id) as counttags
from tagset
where object_id = <some expression to indicate the current object id>
group by tag_id
) g
on t.id = g.tag_id
order by g.counttags desc