Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

database - Passing column name as parameter in MySQL

Is it possible to do something like this:

SELECT template_id as id FROM templates WHERE ? IN template_allowed_parent_templates

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

It's not clear what you are attempting to do.

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

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.

As a simple demonstration:

  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)

or

WHERE FIND_IN_SET( ? ,template_allowed_parent_templates)

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...