如何查找 MySQL 表中的列数?
mysqlmysqli database
要查找 MySQL 表中的列数,请使用 count(*) 函数和 information_schema.columns 以及 WHERE 子句。让我们看一个例子。
创建表。
mysql> create table NumberOfColumns -> ( -> id int, -> FirstName varchar(100), -> LastName varchar(100), -> Age int, -> Address varchar(100) -> ); Query OK, 0 rows affected (0.70 sec)
将记录插入表中。
mysql> insert into NumberOfColumns values(1,'Shane','Watson',36,'Australia'); Query OK, 1 row affected (0.15 sec) mysql> insert into NumberOfColumns values(2,'Carol','Taylor',24,'US'); Query OK, 1 row affected (0.13 sec)
显示所有记录。
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)