我有一个领域它有逗号分隔的ID,所以我想从所选的id中找到,这是我的代码, .get(function(req, res) { knex.select('*') .from('exam') .whereRaw('? = any(regexp_split_to_array(student_id))', [req.params.id]) .then(functi
.get(function(req, res) {
knex.select('*')
.from('exam')
.whereRaw('? = any(regexp_split_to_array(student_id))', [req.params.id])
.then(function(rows) {
//return res.send(rows);
console.log(rows);
})
.catch(function(error) {
console.log(error)
});
});
===>虽然我使用KNEX它会给出一个像这样的错误,
{ error: function regexp_split_to_array(text) does not exist
name: 'error',
length: 220,
severity: 'ERROR',
code: '42883',
detail: undefined,
hint: 'No function matches the given name and argument types. You might need to add explicit type casts.',
position: '37',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_func.c',
line: '523',
routine: 'ParseFuncOrColumn'
}
>在student_id列中,我有这样的ID,33,34,35,36
>在req.params.id我只有一个像35这样的ID.
>所以我想在同一个表中包含35个ID的行.
===>所以我只想要两排(2,3),因为它包含ID = 35.
假设你正在使用PostgreSQL数据库(我看到你在屏幕截图上使用phpPgAdmin).您可以使用 regexp_split_to_array函数将字符串转换为数组(显然:).并使用any执行搜索结果数组.在SQL语言中,它可以这样写
select '35' = any(regexp_split_to_array('33,34,35,36', E','));
在您的查询中,您可以替换.where
.whereRaw("? = any(regexp_split_to_array(student_id, E','))", [req.params.id])
但请记住,这可能是性能繁重的请求,因为每行执行字符串拆分操作.更好的方法(假设项目必须在一行中包含数组值)是将student_id存储在Array类型中,并在student_id列上添加gin索引并执行搜索操作,如this
select * from table where student_id @> '{35}';
