【问题标题】:Search all tables for a string and sort by number of occurrences of that string in a row (SQLite)在所有表中搜索字符串并按该字符串在一行中出现的次数排序(SQLite)
【发布时间】:2020-09-12 02:36:32
【问题描述】:

假设我的数据库中有 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 中的列名以显示它们不相关。

【问题讨论】:

  • 如果这些标题和正文相关,它们应该在一个表中并被引用。
  • 不是,我应该改一下更清楚。

标签: sql string sqlite sql-order-by union


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2021-12-02
    • 1970-01-01
    • 2020-12-06
    • 2018-07-27
    • 2011-03-22
    相关资源
    最近更新 更多