将表计数添加到我的数据库列表中

时间:2016-05-04 14:10:48

标签: php mysql join

我想列出所有自定义数据库:

SELECT `SCHEMA_NAME` AS 'Database',
       `DEFAULT_CHARACTER_SET_NAME` AS 'Character Set',
       `DEFAULT_COLLATION_NAME` AS 'Collation'
  FROM `information_schema`.`SCHEMATA`
  WHERE `SCHEMA_NAME` NOT IN ('information_schema','mysql','performance_schema')
  ORDER BY `SCHEMA_NAME` ASC

但我想在每个数据库中包含表的数量:

SELECT `TABLE_SCHEMA`, COUNT(*)
  FROM `information_schema`.`TABLES`
  WHERE `TABLE_SCHEMA` NOT IN ('information_schema','mysql','performance_schema')
  GROUP BY `TABLE_SCHEMA`

...在一张表中:

[
  0 => [ 'Database'=>'customDb1', ..., 'Table Count'=>3 ],
  1 => [ 'Database'=>'customDb2', ..., 'Table Count'=>8 ],
  2 => [ 'Database'=>'customDb3', ..., 'Table Count'=>0 ]
]

我知道运行第一个查询,在PHP中循环遍历每个数据库,并运行第二个查询的效率远远低于使用表格JOIN之类的东西,但我只是没有抓住{ {1}}语法。 Lynda tutorial我正在通过语言的这个相当(可能)复杂的部分进行调整,而我尝试的所有内容都会引发错误或错误结果。

我确信这是开发人员创建MySQL数据库接口的常见查询。如何使用 MySQL查询将表计数添加到我的数据库列表中?

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT s.`SCHEMA_NAME` AS 'Database',
       s.`DEFAULT_CHARACTER_SET_NAME` AS 'Character Set',
       s.`DEFAULT_COLLATION_NAME` AS 'Collation',
       COALESCE(COUNT(t.`TABLE_SCHEMA`),0) as table_cnt
FROM `information_schema`.`SCHEMATA` s
LEFT JOIN `information_schema`.`TABLES` t
 ON(s.`SCHEMA_NAME` = t.`TABLE_SCHEMA`)
WHERE s.`SCHEMA_NAME` NOT IN ('information_schema','mysql','performance_schema')
GROUP BY s.`SCHEMA_NAME`
ORDER BY s.`SCHEMA_NAME` ASC