这似乎应该简单易行,但我并不聪明。我试图通过单个查询总结同一服务器上多个数据库中的主机数。总结主机数量的数据库本身是从查询中派生出来的。
获取数据库列表:
mysql> select name from db1.companies where status = 'active';
+---------------------+
| name |
+---------------------+
| companyA |
| companyB |
| companyC |
...
获取每个数据库的主机数总和:
SUM(
select count(id) from companyA.hosts
select count(id) from companyB.hosts
select count(id) from companyC.hosts
...
)
答案 0 :(得分:2)
您必须使用预准备语句来获得所需的结果:
SELECT
GROUP_CONCAT(
CONCAT(
'(SELECT count(id) FROM `',
name,
'`.`hosts`)') SEPARATOR ' + ')
FROM
db1.companies
WHERE
status = 'active'
INTO @sql;
SET @sql := CONCAT('SELECT ', @sql);
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
来自SELECT @sql
的输出:
@sql
-------------------------------------------------------------------------
SELECT (SELECT count(id) FROM `companyA`.`hosts`) +
(SELECT count(id) FROM `companyB`.`hosts`) +
(SELECT count(id) FROM `companyC`.`hosts`)
因此,@sql
变量保存需要执行的动态sql语句,以获得所需的结果。
答案 1 :(得分:0)
假设数据库名称正确并且每个数据库都包含一个名为Hosts的表,我们仍然需要在查询中包含模式名称。因此,只需将<schema>
替换为您拥有的架构名称,然后运行以下查询即可获得总和。
;WITH CTE AS (
select count(id) AS [HostSum] from companyA.<schema>.hosts
UNION ALL
select count(id) AS [HostSum] from companyB.<schema>.hosts
UNION ALL
select count(id) AS [HostSum] from companyC.<schema>.hosts
)
SELECT SUM([HostSum]) AS [HostSum] FROM CTE
如果您无法使用公用表表达式,则可以使用以下命令:
SELECT SUM([HostSum]) AS [HostSum] FROM (
select count(id) AS [HostSum] from companyA.<schema>.hosts
UNION ALL
select count(id) AS [HostSum] from companyB.<schema>.hosts
UNION ALL
select count(id) AS [HostSum] from companyC.<schema>.hosts
) AS A