要查找MySQL表中的列数,请使用带有information_schema.columns和WHERE子句的count(*)函数。让我们来看一个例子。
创建一个表。
mysql> create table NumberOfColumns -> ( -> id int, -> FirstName varchar(100), -> LastName varchar(100), -> Age int, -> Address varchar(100) -> );
将记录插入表中。
mysql> insert into NumberOfColumns values(1,'Shane','Watson',36,'Australia'); mysql> insert into NumberOfColumns values(2,'Carol','Taylor',24,'US');
显示所有记录。
mysql> select *from NumberOfColumns;
这是输出。
+------+-----------+----------+------+-----------+ | id | FirstName | LastName | Age | Address | +------+-----------+----------+------+-----------+ | 1 | Shane | Watson | 36 | Australia | | 2 | Carol | Taylor | 24 | US | +------+-----------+----------+------+-----------+ 2 rows in set (0.00 sec)
现在,让我们看看计算表中列数的语法。
SELECT count(*) AS anyName FROM information_schema.columns WHERE table_name =’ yourTableName’;
在示例表中将上述语法应用为名称'NumberOfColumns'。
mysql> SELECT count(*) AS NUMBEROFCOLUMNS FROM information_schema.columns -> WHERE table_name ='NumberOfColumns';
这是输出。
+-----------------+ | NUMBEROFCOLUMNS | +-----------------+ | 5 | +-----------------+ 1 row in set (0.00 sec)
查找列数的备用查询。
SELECT COUNT(*) AS anyName FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'yourDatabaseName' AND table_name = 'yourTableName';
将第二个查询应用于名称为“ business”的数据库。
mysql> SELECT COUNT(*) AS NUMBEROFCOLUMNS FROM INFORMATION_SCHEMA.COLUMNS -> WHERE table_schema = 'business' AND table_name = 'NumberOfColumns';
输出显示列数。
+-----------------+ | NUMBEROFCOLUMNS | +-----------------+ | 5 | +-----------------+ 1 row in set (0.00 sec)