首先,我从两个不同的数据库中选择db1和db2。从每个数据库。在db1上,我根据一列中基于该列中数据的条件计算结果。同样适用于db2。
SELECT
(SELECT COUNT(*) FROM db1.table1) AS Column1,
(SELECT COUNT(*) FROM db1.table1 where
table1.X ='a') AS Column2,
(SELECT COUNT(*) FROM db1.table1 where
table1.X = 'b') AS Column3,
(SELECT COUNT(*) FROM db1.table1 where
table1.X = 'c') AS Column4,
(SELECT COUNT(*) FROM db1.table1 where
table1.X = 'd') AS Column5,
(SELECT COUNT(*) FROM db1.table1 where
table1.X = 'e') AS Column6,
(SELECT COUNT(*) FROM db2.table2 where
table2.Y = 'f') AS Column7,
(SELECT COUNT(*) FROM db2.table2 where
table2.Y = 'g') AS Column8,
(SELECT COUNT(*) FROM db2.table2 where
table2.Y = 'h') AS Column9,
(SELECT COUNT(*) FROM db2.table2 where
table2.Y = 'i') AS Column10;
答案 0 :(得分:2)
如果目标是获取信息,但它不必完全那些列字段名称结果,那么我将使用两个查询:
SELECT `X`,count(*) as `c` FROM `table1` GROUP BY `X` WITH ROLLUP;
SELECT `Y`,count(*) as `c` FROM `table2` GROUP BY `Y` WITH ROLLUP;
您需要遍历每个查询的结果。除最后一行外,每行将有一个标识符(X或Y)和一个计数(c)。最后一行将具有NULL(命名可能会有所不同,具体取决于您用于进行查询的语言 - PHP,Python等),用于标识符和计数总数。
这样做的另一个好处是,如果您要添加要计算的X或Y的新值,查询将不会更改。
答案 1 :(得分:0)
你有没有尝试过类似的东西:
SELECT
MAX(Column1) AS Column1,
MAX(Column2) AS Column2,
MAX(Column3) AS Column3,
MAX(Column4) AS Column4,
MAX(Column5) AS Column5,
MAX(Column6) AS Column6,
MAX(Column7) AS Column7,
MAX(Column8) AS Column8,
MAX(Column9) AS Column9,
MAX(Column10) AS Column10
FROM
(SELECT
COUNT(X) AS Column1,
SUM(X = 'a') AS Column2,
SUM(X = 'b') AS Column3,
SUM(X = 'c') AS Column4,
SUM(X = 'd') AS Column5,
SUM(X = 'e') AS Column6,
NULL AS Column7,
NULL AS Column8,
NULL AS Column9,
NULL AS Column10
FROM
_ds_stack_table1 AS table1 UNION ALL SELECT
NULL AS Column1,
NULL AS Column2,
NULL AS Column3,
NULL AS Column4,
NULL AS Column5,
NULL AS Column6,
SUM(Y = 'f') AS Column7,
SUM(Y = 'g') AS Column8,
SUM(Y = 'h') AS Column9,
SUM(Y = 'i') AS Column10
FROM
_ds_stack_table2 AS table2) D;
SQL小提琴链接: http://sqlfiddle.com/#!9/1eb5cf/1/0