在MySQL中将列名作为参数传递 [英] Passing column name as parameter in MySQL

查看:291
本文介绍了在MySQL中将列名作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行以下操作:

Is it possible to do something like this:

SELECT template_id as id FROM templates WHERE ? IN template_allowed_parent_templates

所以我想看看给定的ID是否在该列中. 如果没有,我该如何仅使用MySQL来解决此问题?

So I want to see if a given ID is in the column. If not, how can I fix this with only MySQL?

推荐答案

就将列名作为参数传递给MySQL(标题中的问题)而言,这在SQL语句中是不可能的. SQL语句中的标识符(例如表名和列名)必须是SQL文本的一部分.那些不能与绑定占位符一起传递.

As far as passing a column name as a parameter in MySQL (the question in the title), that's not possible in a SQL statement. The identifiers in a SQL statement (e.g. the table names and column names) must be part of the SQL text. Those can't be passed in with a bind placeholder.

IN比较运算符需要包含在括号中的值的列表,或者期望包含在括号中的SELECT查询,该查询返回一组值.

The IN comparison operator expects a list of values enclosed in parens, or a SELECT query enclosed in parens that returns a set of values.

不清楚您要做什么.

我怀疑template_allowed_parent_templates是表中的一列,并且它包含用逗号分隔的值列表. (发抖)

I suspect that template_allowed_parent_templates is a column in the table, and it contains a comma separated list of values. (shudder.)

我怀疑您可能正在寻找MySQL FIND_IN_SET 字符串函数,该函数将搜索"逗号分隔的列表以获取特定值.

I suspect you might be looking for the MySQL FIND_IN_SET string function, which will "search" a comma separated list for a particular value.

作为一个简单的演示:

  SELECT FIND_IN_SET('5', '2,3,5,7')
       , FIND_IN_SET('4', '2,3,5,7')

当指定的值是找到的"时,该函数返回一个正整数.您可以在谓词中使用该函数,例如

The function returns a positive integer when the specified value is "found". You can make use of that function in a predicate, e.g.

WHERE FIND_IN_SET(id,template_allowed_parent_templates)

WHERE FIND_IN_SET( ? ,template_allowed_parent_templates)

(之所以起作用,是因为在MySQL中,在布尔上下文中将一个正整数评估为TRUE.)

(This works because in MySQL a positive integer is evaluated as TRUE in a boolean context.)

我只是在猜测您要完成的任务.

I'm only guessing at what you are trying to accomplish.

这篇关于在MySQL中将列名作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆