mysql order by max matches field value

时间:2014-06-22 18:02:16

标签: php mysql

我总共有三张桌子

table:Links

id | name | cat_id | weight
1 | test1 | 1 | 5
2 | test2 | 1 | 10
3 | test3 | 1 | 15
4 | test4 | 1 | 2

table:Tags

id | name | link_id 
1 | tag1 | 1 
2 | tag2 | 1 
3 | tag1 | 2 
4 | tag2 | 2 
5 | tag1 | 3 
6 | tag2 | 4 

这里

test1 have tags like: tag1,tag2
test2 have tags like: tag1,tag2
test3 have tags like: tag1
test4 have tags like: tag2

所以我想要最接近的标签匹配表单test 1

所以结果应为: test2,test3,test4

取决于标签匹配和重量

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT(l.name) AS link 
FROM links l INNER JOIN tags t ON l.id = t.link_id 
AND l.id <> 1 GROUP BY t.link_id ORDER BY COUNT(t.link_id) DESC

SQLFIDDLE DEMO