在所有表中搜索字符串,并按该字符串连续出现的次数进行排序SQLite

问题描述

可以说我的数据库中有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

我应该在sqlite中运行哪个查询以获得这样的结果?

编辑:更改了B和C中的列名称,以显示它们不相关。

解决方法

您可以使用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