如何查询sqlite数据库以获取两列搜索关键字之后的下一个可用字符列表。例如,如果搜索关键字为'and',并让列为firstname和lastname:
And[y] Xyz
And[r]ew And[z]
Xyz And[o]n
Mirand[a] Lorand[e]
那么我应该得到字符[y,r,z,o,a,e]。
我尝试使用substr和instr,但是我无法编写一个查询,同时查询姓和名,并在两个查询中都返回下一个字符。
使用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
参见演示。
结果:
| 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
)
参见演示。
结果:
| chars |
| ----------- |
| y,r,z,o,a,e |
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句