如何在 MySQL 表中查找列数?
要查找 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)
广告