问题描述
可以说我的数据库中有3张这样的表。
table A table B table C
id|title|body id|name |desc id|user |comment
1 |xx |xy 1 |zy |yz 1 |zz |yz
2 |xyz |yy 2 |xx |xx 2 |xx |xy
3 |zy |xx 3 |yy |yy 3 |yyy |yz
当搜索字符串为“ x”时,结果应为
|col1 |col2|
|xx |xx | -- from table B,because 4 occurrences
|xx |xy | -- from table A,because 3 occurrences
|xx |xy | -- from table C,because 3 occurrences
|zy |xx | -- from table A,because 2 occurrences
|xyz |yy | -- from table A,because 1 occurrence
解决方法
您可以使用union all
从三个表中进行匹配。然后,您要按匹配字符数对结果进行排序。一种方法是将原始字符串的长度与删除了搜索字符的字符串的长度进行比较。
select title col1,body col2 from a where title like '%x%' or body like '%x%'
union all select name,descr from b where name like '%x%' or descr like '%x%'
union all select user,comment from c where user like '%x%' or comment like '%x%'
order by
length(col1)
+ length(col2)
- length(replace(col1,'x',''))
- length(replace(col2,'')) desc