Sqlite 如何拆分列,然后将拆分列表与另一个列表进行比较?
我需要从表中选择一个值,将其转换为一个列表,然后在该列表中搜索,如果它在另一个列表中,则只有一个必须匹配 我有一张如下所示的表:Sqlite 如何拆分列,然后将拆分列表与另一个列表进行比较?,sqlite,Sqlite,我需要从表中选择一个值,将其转换为一个列表,然后在该列表中搜索,如果它在另一个列表中,则只有一个必须匹配 我有一张如下所示的表: _id name group 1 Bob mathematics,science,information technology...(list can be any size) 2 John science,mathematics,natural science,life orientation...(list can
_id name group
1 Bob mathematics,science,information technology...(list can be any size)
2 John science,mathematics,natural science,life orientation...(list can be any size)
我有以下数组:
arr = [science,mathematics]
我需要通过逗号分隔符拆分组列
["mathematics","science","information technology"]
然后将此列表与我的arr
数组进行比较。如果其中1个匹配,则返回所有字段
我尝试了substr
和instr
,但无法使其工作
SELECT substr(groups, 1, pos-1) AS g FROM (SELECT groups, instr(groups, ',') AS pos FROM courses WHERE _id = 2);
但这只返回第一个。不确定这在sqlite3中是否可行,因为没有添加库
这就是需要发生的事情:
SELECT * FROM subject WHERE ["mathematics","science","information technology"] in ("science","mathematics")
这里有一个使用的方法。其思想是:创建一个虚拟视图来标记“组”列。它基于substr/instr方法,将每个group元素放在视图的一行中。以下是一个示例查询:
注意:要“查看”glist的外观,请将
select distinct….
查询替换为select*from glist
,这就是genius!真是太棒了!
WITH RECURSIVE
glist(id, head, rest) AS (
select id,
CASE when instr(groups,",") = 0 then groups else substr(groups,1,instr(groups,',')-1) END, -- head
CASE when instr(groups,',') = 0 then groups else substr(groups,instr(groups,',') + 1) END --rest
from subjects
UNION ALL
SELECT id, substr(rest,1,instr(rest,',') - 1), --head
substr(rest,instr(rest,',')+1) -- rest
FROM glist
WHERE id = id
and instr(rest,',') !=0 -- base case
)
select distinct subjects.*
from glist g
JOIN subjects on subjects.id = g.id
where head in ('science','mathematics')
order by id