查询以在多个表上的字段上计算不同不工作
Query to count distict on a field on multiple tables not working
SQL 查询:
Select count(distinct signature)
from (Select table_name
from information_schema.tables
where table_schema="Log" and table_name like "%ERROR_%")
AS mytable;
预期输出: 所有表中不同 "Signature" 的数量。
实际输出: 'field list' 中的未知列 'signature';
注意:我所有的表都有签名作为字段名
嗯,你的子查询是这样开始的:
Select table_name from information_schema.tables
所以您要拉入的可用列是 "table_name"。
因此,如果您尝试 select 来自该子查询的签名,它会告诉您没有这样的列。
你可能想做这样的事情(伪代码):
query(
Select table_name
from information_schema.tables
where table_schema="Log" and table_name like "%ERROR_%"
)
$sql = '';
$sep = '';
while ($row = fetch_assoc()) {
$sql .= $sep."SELECT signature FROM $row[table_name] ";
$sep = 'UNION ALL ';
}
$sql = "SELECT COUNT(DISTINCT signature) as c FROM ($sql)";
query($sql);
$row = fetch_assoc()
echo "There are $row[c] distinct signatures.<br />\n";
您似乎在 mysql 端尝试动态查询。请检查这个...
-- Step1. prepare your select query here
set @sqlQuery :=
(select
GROUP_CONCAT(
concat(' SELECT \'',table_name,'\' as col1, COUNT(*) as countItem FROM ', table_name)
SEPARATOR ' UNION ALL '
) from information_schema.tables as t
where t.table_schema="Log" and t.table_name like "%ERROR_%");
-- Step2. execute the dynamic query
prepare stmt from @sqlQuery;
execute stmt;
drop prepare stmt;
SQL 查询:
Select count(distinct signature)
from (Select table_name
from information_schema.tables
where table_schema="Log" and table_name like "%ERROR_%")
AS mytable;
预期输出: 所有表中不同 "Signature" 的数量。
实际输出: 'field list' 中的未知列 'signature';
注意:我所有的表都有签名作为字段名
嗯,你的子查询是这样开始的:
Select table_name from information_schema.tables
所以您要拉入的可用列是 "table_name"。
因此,如果您尝试 select 来自该子查询的签名,它会告诉您没有这样的列。
你可能想做这样的事情(伪代码):
query(
Select table_name
from information_schema.tables
where table_schema="Log" and table_name like "%ERROR_%"
)
$sql = '';
$sep = '';
while ($row = fetch_assoc()) {
$sql .= $sep."SELECT signature FROM $row[table_name] ";
$sep = 'UNION ALL ';
}
$sql = "SELECT COUNT(DISTINCT signature) as c FROM ($sql)";
query($sql);
$row = fetch_assoc()
echo "There are $row[c] distinct signatures.<br />\n";
您似乎在 mysql 端尝试动态查询。请检查这个...
-- Step1. prepare your select query here
set @sqlQuery :=
(select
GROUP_CONCAT(
concat(' SELECT \'',table_name,'\' as col1, COUNT(*) as countItem FROM ', table_name)
SEPARATOR ' UNION ALL '
) from information_schema.tables as t
where t.table_schema="Log" and t.table_name like "%ERROR_%");
-- Step2. execute the dynamic query
prepare stmt from @sqlQuery;
execute stmt;
drop prepare stmt;