Wildcard for a column name in the WHERE clause of a SELECT statement?

拥有回忆 提交于 2019-12-25 01:33:47

问题


Is it possible to have a wildcard in a column name specified in the WHERE clause? I want to select something but only if a bunch of columns match a certain value (1 in this case). For example:

SELECT COUNT(id) FROM records WHERE *_check = 1

I have a bunch of columns that have _check as the suffix and it would be really nice to use something similar to the above code (which doesn't work).


回答1:


You could query the information_schema to get the columns in one query

SELECT column_name FROM information_schema.columns
WHERE table_schema = 'foo'
 AND table_name = 'bar'
 AND column_name LIKE '%_check'

and build your query from the result (pseudo code)

query = "SELECT COUNT(id) FROM records WHERE ";

foreach columName in columnNames
   query = query + " " + column_name + " = 1 OR "
next

query = TrimLastOr(query);

But I wouldn't recommend that because mysql information_schema query have a poor performance since they read from disk for every query.

Better: Use a view that returns

SELECT id FROM records WHERE col1_check=1 or col2_check=2 ...

so you can use it in your logic on multiple places, and only have to update the view if you add another _check column.




回答2:


No.

If you want to do something like this, you need the equivalent of dynamic SQL.



来源:https://stackoverflow.com/questions/10602888/wildcard-for-a-column-name-in-the-where-clause-of-a-select-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!