mysql get column name when column value matches constraint

≡放荡痞女 提交于 2019-12-11 05:42:02

问题


I'm trying to get column names from a table. I want to supply the row id and I want only the column names for which the value of that column for the specific row (identified by the id) is "true" (my table has a bunch of boolean fields).

I want something like:

SELECT COLUMN_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME.value = true
        AND TABLE_THE_COLUMN_IS_FROM.id = "some_id"

Where .value would be variable, basically checking each column to see if it were true.

I know I can just get the row's values and iterate through, returning only those with value true, but I wanted to see if there is a way to do it all in one step. Thanks in advance to anyone who knows!


回答1:


There is no means in one query to dynamically scan through the table's schema and inspect its values. The best way to achieve what you want is the one you suggested: query for the row client-side and then cycle through the columns searching for the values you seek. The other alternative is to query for the table schema using the INFORMATION SCHEMA views client-side, build a SQL statement with a where clause that looks for a True value in all the boolean columns, execute that and inspect the results.




回答2:


This is probably going to be rather ugly no matter how you cut it, but here's one option:

select columns.column_name
from bool_table
inner join information_schema.columns
on columns.table_schema = 'your_db'
and columns.table_name = 'bool_table'
and ((columns.column_name = 'bool_1' and bool_table.bool_1 = 1)
     or (columns.column_name = 'bool_2' and bool_table.bool_2 = 1))
where bool_table.id = 25

You could also potentially query information_schema.columns to dynamically generate the list of column statements so that you could dynamically generate the query, and even execute it in a stored proc using dynamic sql in mysql.



来源:https://stackoverflow.com/questions/5590004/mysql-get-column-name-when-column-value-matches-constraint

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