我需要从表中选择一个值,将其转换为列表,然后搜索该列表(如果它在另一个列表中),只需匹配一个。
我有一个如下表:
_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
数组进行比较。如果其中之一匹配,则返回所有字段。
我尝试了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")
答案 0 :(得分:1)
这是使用WITH RECURSIVE的方法。想法是:创建一个虚拟化视图,该视图将“ group”列标记化。它基于您的substr / instr方法,将每个组元素放在视图的一行中。这是一个示例查询:
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
NB要“查看” glist
的样子,将select distinct....
查询替换为select * from glist