Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Select Column names containing a string

Tags:

mysql

I am trying to get data from columns containing a particular string in their name in my case it it PLA. Though their is a way to select where the values are like as in MySQL query String contains. Is there a similar way for the column name?

SELECT COLUMN NAMES LIKE '%PLA%' FROM `TABLENAME` WHERE MONTH=? AND YEAR=?
like image 496
norbdum Avatar asked Nov 08 '13 03:11

norbdum


1 Answers

SELECT COLUMN NAMES is not valid in MySQL. There are similar things such as DESCRIBE [table]; or SHOW COLUMNS FROM [table];, but you can't put WHERE clauses on them. Much better is to use the INFORMATION_SCHEMA virtual DB e.g. -

SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS`
 WHERE `TABLE_SCHEMA`='[database name]' and `TABLE_NAME`='[table name]'
 AND   `COLUMN_NAME` LIKE '%PLA%'

See http://dev.mysql.com/doc/refman/5.6/en/columns-table.html for more information.

like image 114
ddisisto Avatar answered Sep 28 '22 13:09

ddisisto