How to count the columns of a MySQL query when the number of columns returned is dynamic?

Is it possible to get a count of the number of columns returned by a query? This can be easily done with a linked scripting language like php, but I'm looking for a db-only solution.

Example:

CountCols(SELECT 'a','b','c')
    => 3
CountCols(SELECT * FROM information_schema.session_variables)
    => 2

      

+3


source to share


3 answers


Will this work for you?

select 
    count(*)
from
    `information_schema`.`columns`
where
    `table_schema` = 'my_table_schema' and `table_name` = 'my_table_name';

      

You only need to use table_schema

if the table name exists in multiple databases.




Based on your answer to the answer, you are counting to calculate the dynamic number of columns. You can do this with a temporary table, but you cannot access the data in the temporary table without using a patch installation .

It should be noted that there is a similar outstanding SO question that asks how to select columns from a temporary table.

+3


source


Ok, if you want to know the columns in a table, just do:

DESCRIBE `table_name`

      



Otherwise, there is no "real" way to get the number of columns in the select query, since apart from the selection, *

you are selecting specific columns → so you know how many columns you are selecting.

+1


source


You will most likely find your answer: http://dev.mysql.com/doc/refman/5.0/en/columns-table.html

Write a query that takes a table name parameter and then queries the columns of that table and sums it up.

+1


source







All Articles