在显示特定对象的页面上,我需要基于标签显示该对象的相关对象. ´具有最匹配标签的对象应位于顶部.基本上我基本上需要确定每个对象有多少标签与页面上的对象匹配,并显示最佳结果.
我的数据库模式:
Table Object
------------
id
name
Table Tagset
-------------
object_id
tag_id
Table Tag
------------
id
name
最佳答案
这应该做您想要的:
原文链接:https://www.f2er.com/mysql/532035.htmlSELECT 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),3),4),5);