当返回的列数是动态的时,如何计算MySQL查询的列数? [英] How to count the columns of a MySQL query when the number of columns returned is dynamic?

查看:202
本文介绍了当返回的列数是动态的时,如何计算MySQL查询的列数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检索查询返回的列数计数?可以使用绑定脚本语言(例如php)轻松完成此操作,但是我正在寻找仅限db的解决方案.

Is it possible to retrieve the count of the number of columns a query returns? This can be easily done with a bound scripting language such as php, but I'm looking for db only solution.

示例:

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

推荐答案

这对您有用吗?

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

如果表名存在于多个数据库中,则只需使用table_schema.

You only need to use table_schema if the table name exists in more than one database.

根据您的回复评论,您希望计算动态列数.您也许可以使用临时表来执行此操作,但是如果没有安装补丁.

Based on your response comment, you are looking to count a dynamic number of columns. You may be able to do this with a temporary table, but you cannot access the data of a temporary table without possibly installing a patch.

值得注意的是,有一个类似的未解决SO问题询问如何从临时表中选择列.

Of note, there is a similar outstanding SO question asking how to select columns from a temporary table.

这篇关于当返回的列数是动态的时,如何计算MySQL查询的列数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆