如何使用SQL语句获取数据库中的字段/条目数?

有帮助吗?

解决方案

mmm所有表中的所有字段?假设标准(mssql,mysql,postgres),您可以通过information_schema.columns发出查询

  SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 

或按表格分组:

  SELECT TABLE_NAME, COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 
  GROUP BY TABLE_NAME

如果多个模式在同一个DB中具有相同的表名,那么您还必须包含模式名称(即:dbo.Books,user.Books,company.Books等)。否则,您将得到错误的结果。所以最好的做法是:

SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
GROUP BY TABLE_SCHEMA, TABLE_NAME

其他提示

试试这个,这将排除视图,如果你想要视图,请保留where子句

  select count(*) from information_schema.columns c
join information_schema.tables t on c.table_name = t.table_name
and t.table_type = 'BASE TABLE'

听起来这就是你所需要的。

select CountOfFieldsInDatabase = count(*)
from   information_schema.columns

对于任何其他谷歌搜索的读者......

有几种非SQL解决方案,可能对用户有用.. 这是我用的2个。

示例1: 访问VBA:

'Microsoft Access VBA
Function Count_Fields(Table_Name As String) As Integer
    Dim myFieldCount As Integer
    Dim db As DOA.Database
    Dim rs As DAO.Recordset
    Set db = CurrentDb
    Set rs = db.OpenRecordset(Table_Name, dbOpenDynaset)
    myFieldCount = rs.Fields.Count
    'return the count
    Count_Fields = myFieldCount
    'tidy up
    Set rs = Nothing
    Set db = Nothing
End Function

示例2: PHP 5.1:

    <?php
    // PHP5 Implementation - uses MySQLi.
    function countFields ($tableName) { 
    $db = new mysqli('myserver.me.com', 'user' ,'pass', 'databasename');
    if(!$db) {
        echo 'ERROR: Could not connect to the database.';
        } 
    else {
        $rs->$db->query("SELECT * FROM ".$tableName.");
        $fieldCount = $rs->field_count;
        }
    return $fieldCount;
?>

请原谅上面的任何拼写错误 - 希望有人发现这个有用的

select count(column_name) from information_schema.columns 
where table_name = **name of your table here **
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top