在所有表中搜索一个字符串并按该字符串在一行中出现的次数排序(SQLite)
Search all tables for a string and sort by number of occurrences of that string in a row (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, 'x', '')) desc
假设我的数据库中有 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, 'x', '')) desc