SQLite查询以获取包含名字或姓氏的搜索文本的下一个可用字符

时间:2019-06-01 11:36:24

标签: android sqlite android-sqlite

如何查询sqlite数据库以获取两列搜索关键字后的下一个可用字符列表。例如,如果搜索关键字是“ and” 并让列为名字和姓氏:

And[y] Xyz
And[r]ew And[z]
Xyz And[o]n
Mirand[a] Lorand[e]

然后我应该得到字符[y,r,z,o,a,e]。

我尝试使用substr和instr,但是我无法编写一个查询名字和姓氏并返回两个字符的下一个字符。

1 个答案:

答案 0 :(得分:0)

使用UNION ALL作为2列中的值,并使用rowid获得正确的顺序:

select nextchar from (
  select
    1 col, 
    rowid,
    substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
  from names 
  where firstname like '%and%'
  union all 
  select
    2, 
    rowid,
    substr(lastname, instr(lower(lastname), 'and') + 3, 1)
  from names 
  where lastname like '%and%'
) t
order by t.rowid, t.col

请参见demo
结果:

| nextchar |
| -------- |
| y        |
| r        |
| z        |
| o        |
| a        |
| e        |

如果要将结果作为逗号分隔的字符串,请使用group_concat()

select group_concat(nextchar) chars from (
  select nextchar from (
    select
      1 col, 
      rowid,
      substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
    from names 
    where firstname like '%and%'
    union all 
    select
      2, 
      rowid,
      substr(lastname, instr(lower(lastname), 'and') + 3, 1)
    from names 
    where lastname like '%and%'
  ) t
  order by t.rowid, t.col
)

请参见demo
结果:

| chars       |
| ----------- |
| y,r,z,o,a,e |