Marco
Marco

Reputation: 209

MySQL get column names from a query

I want to query the column names from a query, something like this:

SHOW COLUMNS FROM 
(SELECT `f1`, `f2`, `g1`, `g3` FROM `f` INNER JOIN `g` ON `g`.`Id` = `f`.`Id`)

And the result be

FIELD
f1
f2
g1
g3

Of course this query is wrong. But is there a way to do that?

Upvotes: 1

Views: 1509

Answers (1)

Pred
Pred

Reputation: 9042

Why do you need this?

If you want to use it in a procedure or similar, then you are already typed in the column names. If it is a dynamically generated query, use that method which generates the query to get the column names.

If you want to use them in your program, most languages provides functionality to get the resultsets column information.

PDOStatement::getColumnMeta ( int $column ) in PHP with PDO OdbcDataReader.GetSchemaTable() in .NET

This solution is a hack! (and not recommended and also not tested, just a suggestion!)

Create a temporary table based on the query (SELECT .... INTO #temptable) (possibly with a where clause which never evaulates to true (WHERE 0=1), then query that temp tables metadata from INFORMATION_SCHEMA.COLUMNS

Upvotes: 2

Related Questions