所以我有一个试图抓住"相关帖子"的查询.
类别与帖子具有一对多的关系.标签具有多对多关系.所以我的表看起来大致如下:
posts table:
id | category_id | ... | ...
tags table:
id | ... | ...
post_tag intermediate table:
id | post_id | tag_id | ... | ...
Run Code Online (Sandbox Code Playgroud)
所以,如果我已经有一个Post行,那么抓住它的"相关"帖子.我的逻辑大致是我想只抓取属于同一类别的帖子,但是按照与原始帖子匹配的标签数量来订购这些帖子.因此,同一类别中与原始帖子具有完全相同标签的其他帖子应该是非常高的匹配,而仅匹配3/4标签的帖子将在结果中显示较低.
这是我到目前为止:
SELECT *
FROM posts AS p
WHERE p.category_id=?
ORDER BY ( SELECT COUNT(id)
FROM post_tag AS i
WHERE i.tag_id IN( ? )
)
LIMIT 5
Run Code Online (Sandbox Code Playgroud)
BINDINGS:初始帖子类别ID; 初始帖子标签ID;
显然,这不会通过子选择中的正确值来实际排序结果.我在试图考虑如何加入这个以获得正确的结果时遇到了麻烦.
提前致谢!
如果我正确理解你的问题,这就是你要找的:
SELECT p.*,
Count(pt.tag_id) AS ord
FROM posts AS currentpost
JOIN posts AS p
ON p.category_id = currentpost.category_id
AND p.id != currentpost.id
JOIN post_tag AS pt
ON pt.post_id = p.id
AND pt.tag_id IN (SELECT tag_id
FROM post_tag
WHERE post_id = currentpost.id)
WHERE currentpost.id = ?
GROUP BY p.id
ORDER BY ord DESC
Run Code Online (Sandbox Code Playgroud)
绑定:初始posts.id;
你只需要在我的版本中指定当前帖子的 id,这样你就不必事先获取帖子标签并为 in 子句设置适当的格式
编辑:通过避免双重连接帖子,这应该是一个更快的查询,如果您不喜欢用户变量,只需将所有 currentpostid 替换为 ? 和三重绑定 post_id:
set @currentpostid = ?;
select p.*, count(pt.tag_id) as ord
from posts as p,
join post_tag as pt
on pt.post_id = p.id
and pt.tag_id in (select tag_id from post_tag where post_id = @currentpostid)
where p.category_id = (select category_id from posts where id=@currentpostid)
and p.id != @currentpostid
group by p.id
order by ord desc;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |