表结构如下
post表:id,title,content
post_tag表:postId,tagId
一个post其id为10,最多可以有5个tag。需要根据这个post的id获得与他具有最多相同标签的post。
假如post1有t1,t2,t3三个标签
而post2有t1,t2,t3标签,post3有t1,t2的标签,而post4有t1标签
那么根据post1去查找时post2,post3,post4都是符合条件的结果,但是他们的顺序应该是post2,post3,post4.
求这个sql怎么写?最好是mysql的,t-sql也可以,谢谢!
SELECT * FROM POST LEFT JOIN post_tag ON POST.id = post_tag.postId AND post_tag.tagid IN ( SELECT tagId FROM post RIGHT JOIN post_tag ON POST.id = post_tag.postId )
未测试 楼主试一下
谢谢回复。但是不满足要求呀。如何把相同标签最多的排到最前面呢?
@玉开: 好吧 我再改一下
@sym_cn: 不好下SQL 楼主是否考虑 通过程序代码控制呢
@sym_cn: 并非一条SQL能出来的结果集。
@sym_cn:
SELECT p.* FROM post p INNER JOIN ( SELECT COUNT(*) cn,pt.postId FROM post_tag AS pt WHERE pt.tagId IN ( select tagId from post_tag where postId = xx ) GROUP BY pt.postId ) ptc ON p.id = ptc.postId ORDER BY ptc.cn DESC LIMIT 10
搞定了,谢谢你
@玉开: 哈哈 受教了
SELECT p.* FROM post p INNER JOIN ( SELECT COUNT(*) cn,pt.postId FROM post_tag AS pt WHERE pt.tagId IN ( select tagId from post_tag where postId = xx ) GROUP BY pt.postId ) ptc ON p.id = ptc.postId ORDER BY ptc.cn DESC LIMIT 10