我有一个主题库系统。我需要在主题预览页面中实现“相关主题”项目。
每个主题都有颜色和标签,所以在5个表之间我有:
主题
颜色
标签
theme_color
theme_tag
问题是,我只需要收到5个结果,并且必须显示颜色和标签之间有更多匹配的结果。有了这个要求,我不知道从哪里开始。有什么想法吗?
答案 0 :(得分:1)
如果您想要与给定主题共享最多项目的五个主题,您可以尝试以下内容:
DECLARE @target_id_theme INT;
SET @target_id_theme = 1; -- this is the id_theme you want to find similar themes for
SELECT t.id_theme, COUNT(*) as matching_things
FROM theme AS t
LEFT OUTER JOIN theme_color AS tc ON tc.id_theme = t.id_theme
LEFT OUTER JOIN theme_tag AS tt ON tt.id_theme = t.id_theme
WHERE tc.id_color IN (SELECT id_color FROM theme_color WHERE id_theme = @target_id_theme)
OR tt.id_tag IN (SELECT id_tag FROM theme_tag WHERE id_theme = @target_id_theme)
GROUP BY t.id_theme
ORDER BY COUNT(*) DESC
LIMIT 5
未经测试,买家要小心,但我希望你明白这一点。这会为每个颜色或标记创建一个行,该行匹配分配给@target_id_theme的颜色或标记,按计数递减排序,并为您提供前5个。
答案 1 :(得分:0)
试试这个:
SELECT * FROM theme t
FULL OUTER JOIN theme_color tc ON tc.id_theme = t.id_theme
INNER JOIN color c ON c.id_color = tc.id_color
FULL OUTER JOIN theme_tag tt ON tt.id_theme = t.id_theme
INNER JOIN tag ta ON ta.id_tag = tt.id_tag
WHERE tag LIKE '%' + @KEYWORD + '%' OR color LIKE '%' + @KEYWORD + '%' OR title LIKE '%' + @KEYWORD + '%'