13

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

4

5 回答 5

29

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

  SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 

或按表分组:

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

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

SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
GROUP BY TABLE_SCHEMA, TABLE_NAME
于 2009-06-23T16:35:19.783 回答
4

试试这个,这将排除视图,如果你想要视图,请忽略 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'
于 2009-06-23T16:36:05.540 回答
1

听起来这就是你需要的。

select CountOfFieldsInDatabase = count(*)
from   information_schema.columns
于 2009-06-23T16:36:56.960 回答
0
select count(column_name) from information_schema.columns 
where table_name = **name of your table here **
于 2010-02-16T07:33:26.307 回答
0

只是为了任何其他正在谷歌搜索的读者......

有几种非 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;
?>

请原谅上面的任何错字 - 希望有人觉得这很有用

于 2011-02-27T19:09:06.187 回答